Reputation: 183
In java, is it possible that you get a OutOfMemoryError exception, even when there should have enough memory should garbage collection freed more memory? In other words, if there is not enough memory to allocate, will gc be forced to run before throwing the OutOfMemoryError?
Thanks.
Upvotes: 11
Views: 3869
Reputation: 15791
you can get it if the GC is spending too much time trying to free memory and not freeing up much memory by doing so 'java.lang.OutOfMemoryError: GC overhead limit exceeded', see this question.
Upvotes: 5
Reputation: 100
Seems if you write you code appropriate, you will never hit OOM. Because JVM will run gc before it hit OOM.
So if you hit OOM, it most probably your code got some memory leak. Check this.
http://www.ibm.com/developerworks/library/j-leaks/
Upvotes: 1
Reputation: 47709
GC is forced to run before OutOfMemoryError is thrown. If the JVM implements several varieties of GC (such as "concurrent" or "partial") a "stop the world" GC will be run before the JVM gives up, so every possible effort has been made to avoid the error.
The exception that's being cited is that if the GC repeatedly runs and only recovers a miniscule amount of storage (and heap size cannot be further expanded) then it will toss in the towel rather than continue to run in "crawl" mode. In theory, for this case, slightly increasing heap size would allow a "good" application to run OK, but an app that is slowly chewing up heap (which is not unusual) would not benefit from a slight heap increase, and would encounter the same failure only slightly later.
[It should be noted that in cases where GC is running too frequently increasing the heap size may significantly reduce GC overhead, if the application is well-behaved and just coincidentally happens to be running near the heap limit. (Of course, increasing the heap size to greater than available RAM will usually make the app run slower.)]
Upvotes: 2
Reputation: 121712
There is one case where you might get an OOM which is neither heap related or address space related: it is when the JVM decides the GC takes too much time to run.
See here.
In other words, the answer to your original question, that is, "if there is not enough memory to allocate, will gc be forced to run before throwing the OutOfMemoryError", is yes.
(you will see from the link above that the ratio is 98%/2% for gc/running code, which is very high already)
(note 2: this is for Sun's/Oracle's JVM, no idea for other implementations)
Upvotes: 6
Reputation: 1500225
The GC will generally try to find memory before OutOfMemoryError
is thrown, but very occasionally I've seen reproducible examples where the garbage collector doesn't quite keep up, and a call to System.gc()
prevents the exception.
That's very much the exception (no pun intended) rather than the rule though - you should almost never try to provoke garbage collection yourself.
Upvotes: 1