Java and memory

Status
Not open for further replies.
I have a program that needs to use a lot of memory. (Counts word frequencies in a Wikipedia dump). Well, I gent into project settings and told it that I'll be needing half a gig at least (-Xms512m -Xmx1024m). I also run System.gc() and System.out.println(Runtime.getRuntime().freeMemory()) every 10 seconds. But the program still crashes. Its dying words are that there's still more than 300 MB left. There's no way all that memory can be used up in the next 9 seconds. And I'm quite certain I don't run out of physical memory, as I have tons of it, plus swap space.

My VM is OpenJDK 6 19.0-b09 on Ubuntu 10.10.
 

dezzroy

Ars Scholae Palatinae
604
Some things off the top of my head...

- Did you try the Sun/Oracle JVM and compare results? I imagine there may be some differences in the way it handles memory, could be worth trying.

- If all else fails, maybe refactor your code to use less memory... as TooLazy mentioned, maybe roll your own paging to/from disk process for things that need not reside in RAM at a given moment. This, of course, will slow the program down, waiting for disk operations.
 
First, don't call System.gc(). You don't need to call it for the system to GC. It does anyway, and it knows the best time to do it; you don't. Secondly, Runtime.getRuntime().freeMemory() is a question, not a command. It asks the runtime system how much free memory there is. It doesn't tell the runtime to free memory. You can't just say "free me more memory" because any memory that can be freed will be freed before your program runs out of memory.

Your problem is your program simply uses too much memory. Either your algorithm uses a shitload of memory so that you need to allocate more memory or optimize the algorithm, or you have a memory leak. Either way, the only easy way out is throwing more memory at the program; if that doesn't work, you need to change your code.
 
Tiiba":2sp86ind said:
"First, don't call System.gc(). You don't need to call it for the system to GC. It does anyway, and it knows the best time to do it; you don't."

It has helped in the past.
Then I really wonder what you were doing and how it helped. When your memory fills up with garbage, the VM will run a GC. If a program runs out of memory without System.gc(), it will run out of memory with System.gc(). If you're very smart and know the internals of the VM and specific patterns with which your program uses memory, you could conceivably call System.gc() to improve performance. The optimization wouldn't be portable though and it would likely be small. I don't see what other way you could benefit from it.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
It has helped in the past.

There are specific scenarios this can truly help (rather than paper over the cracks of un-managed resource leaks). People that know how to do that shouldn't be asking the question you're asking because they would know to run a heap profiler and *find out what's happening*. They also wouldn't bother talking about physical memory since they would know that its addressable memory that matters in this instance.

Sorry if that's somewhat ego-deflating.

You haven't even said what data structures you're storing the mapping in. A hash? a DAWG? are you pre-allocating based on the input set size?
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Are you referring to calling System.gc() to get the VM to run finalizers that free resources? I can see how that could help but that whole scenario is fail on top of fail.

That was the paper over the cracks thing I referred to yes (and it is abhorrent and foolish).

There are some latency sensitive scenarios, where you know that you have some spare time to do a level2 GC and there's a good chance that doing so will reduce the probability of a full GC on your future hot calls to zero. This can also be a net throughput win, but only if you things like needless dirtying of your cache and mid life crisis of needless gen 1-2 promotions that you wouldn't normally get don't swamp you.

Often in these situations you can achieve much the same thing by changing your GC entirely to one with reduced throughput but semi concurrent GCs making the trade off explicitly, but some people may not have that option (or may have other areas that benefit from a different 'default' GC based on benchmarks).

It can be a black art when doing it because tiny changes in your apps behavior can skew the results heavily (and realistic testing is hard so you are often forced to suck it and see in production) but should still be approached as a decent scientific effort to start with.

As a side note it can be a useful 'pre-tenuring' strategy too, but then you would only want to do it once (and is pointless on .Net because just dropping things in the LOH is he most effective way to do that).

For anyone to do this without having first taken a good hard look at a memory allocation trace is madness.

Essentially managed platforms can, by default, have a latency impact, and sometimes you need to do slightly off normal things to work with this (the non generation XNA (and previously Win Phone 7) GC was often a source of this but at least the target hardware was often very rigid so such optimizations had a far higher payoff. I end up looking at this sort of thing quite a lot, but would never suggest it was a 'normal' or remotely sensible thing for most people to look at.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
If you need half a gig of ram for a word frequency analysis you're doing it wrong.
Maybe we should start there instead of at the ass-end of the problem of how to wedge a cow into a gopher hole.

I'm playing with cocos2d (iPhone game library in obj-c) and needed a word dictionary. I initially tossed it into a trie. A rough estimate is it took about 8megs of ram and required a stack size sufficient to recurse the longest word. (memory allocation was over the top in practice as it was fragmented to hell and back, but it wasn't outrageous for a PC; just brutal for a phone))

It would have been trivial to use the resulting trie to gather word counts in a reasonably efficient manner. (add word to trie, or increment count leaf of trie)

Certainly wouldn't have come close to half a gig.

(when it became apparent the trie would need to be optimized I shoved the dictionary into an NSSet instead and found it to be blazingly fast and not as memory hungry as I thought it would be; however I may need to switch back to a trie in the future for other functionality you get 'for free'; like prefix handling.
I pre-configured the NSSet to expect the number of words read, although a generous estimate would work fine too. Cocoa libraries may choose alternate algorithms, or hashing methods based on expected, or actual capacity; nsset uses hashes for lookups )
 
I don't suppose the algorithm looks like:

Code:
// Read HOOG file into oneGiantString
Map<String, Integer> frequencies = new HashMap<String, Integer>();
while(oneGiantString.length() > 0) {
  String currentChar = oneGiantString.subString(0, 1);
  Integer count = frequencies.get(currentChar);
  if (count == null) {
    count = 0;
  }
  count++;
  frequencies.put(currentChar, count);
  oneGiantString = oneGiantString.substring(1,oneGiantString.length() - 1);
}
// display frequency chart or do further processing

Whole lot of garbage generation, but it should be handled ... and should get better over time ...

* forgive me if the substring call is one-based versus zero-based ... http://xkcd.com/163/ (edit: bugfix)
 
What exception does your program crash with?

This.

At least for the Sun/Oracle JVM, there are several ways that it can run out of memory, and each of them has a different resolution.

But calling the gc directly is usually the wrong decision. We got a ~25% speedup in our app when we added -XX:-DisableExplicitGC and just let the VM figure out when it should run GC. (one of the components we uses was calling GC on its own)

Also, things like -server and the parallel GC options are good for big memory apps. Not sure what OpenJDK supports in this area though.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
aliftedlorax":2qb7nbqs said:
Is the following shell script unsuitable for some reason?

Code:
sed -e 's/\.//g'  -e 's/\,//g' -e 's/ /\
/g' "$1" | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr

(taken from http://tldp.org/LDP/abs/html/abs-guide.html#WF)

That uses the system sort (which is an external sort) to avoid the memory conundrum.

I assume it's an assigned project from a course. The point isn't the answer (the frequency of words used in wikipedia), but writing the code necessary to process the data itself.

Shoving more RAM at a bad process (half a gig to process wikipedia? really!?) isn't the right way to solve the problem.

And, if the problem were about reading the dataset into ram then I'd have to ask if he could use MappedByteBuffer; or whatever else is available to him which would reduce memory impact.

Assuming a dictionary of 250,000 words with an average length of 10 characters you'd be looking at string allocations of 2,500,000 bytes raw data; toss in overhead for references and garbage collection info, etc. and you're still likely under 5,000,000 bytes. Tossed into a HashMap and count the frequencies you're still looking at less than 10Megs. Even if my estimates are off (good chance of it) you are orders of magnitude below a Gig.
 
topham":3f9ioudo said:
Shoving more RAM at a bad process (half a gig to process wikipedia? really!?) isn't the right way to solve the problem.
It depends on what your objective is. If you want to write a general-purpose app or learn how to write good code, fix that shit. If you just want to run a one-off program to get a result, do whatever's easier, which may be throwing more memory at it.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
newwb":1xdp7zum said:
topham":1xdp7zum said:
Shoving more RAM at a bad process (half a gig to process wikipedia? really!?) isn't the right way to solve the problem.
It depends on what your objective is. If you want to write a general-purpose app or learn how to write good code, fix that shit. If you just want to run a one-off program to get a result, do whatever's easier, which may be throwing more memory at it.

Because then the answer is to use the script someone else posted that'll generate the results in short order and move on to something else.

The OP is posting a semi-standard programming problem in a Programming thread. I'd start with the assumption he wants to learn something. Although around here that does often seem to be a poor assumption.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Assuming a dictionary of 250,000 words with an average length of 10 characters you'd be looking at string allocations of 2,500,000 bytes raw data; toss in overhead for references and garbage collection info, etc. and you're still likely under 5,000,000 bytes. Tossed into a HashMap and count the frequencies you're still looking at less than 10Megs. Even if my estimates are off (good chance of it) you are orders of magnitude below a Gig.

On the other hand, if you start with an auto-resizing Dictionary instead of a Set and create duplicate strings while trying to trim() and lowercase() and the dictionary doubles in size every time it needs to reallocate...

"It says I'm out of memory with 300MB left" tells my pyschic debugging that there's a dynamic collection trying to reallocate itself to accomodate more items. Just a WAG.
 
topham":390zzzax said:
newwb":390zzzax said:
topham":390zzzax said:
Shoving more RAM at a bad process (half a gig to process wikipedia? really!?) isn't the right way to solve the problem.
It depends on what your objective is. If you want to write a general-purpose app or learn how to write good code, fix that shit. If you just want to run a one-off program to get a result, do whatever's easier, which may be throwing more memory at it.

Because then the answer is to use the script someone else posted that'll generate the results in short order and move on to something else.

The OP is posting a semi-standard programming problem in a Programming thread. I'd start with the assumption he wants to learn something. Although around here that does often seem to be a poor assumption.

The problem is standard, but Wikipedia has "syntax". I tried (with limited success) to not count structural elements as words.

And the reason I expected to need a lot of memory is because WP is, frankly, large. 2.5 GB after bz2.

I use a SAX parser, to which I pass a burrito of three streams wrapping each other: file, buffered, and bz2 (from Apache). I parse only the contents of "text" tags.

And the purpose of the project is "satisfy curiosity".
 
Status
Not open for further replies.