Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the garbage collector guaranteed to run before Out of Memory Error?

In case the heap is full, the JVM throws an OutOfMemoryError. But is it assured that a (full) garbage collection always takes place before such an exception is thrown?

This would mean that the memory is full only with strong referenced objects (or reachable by GC Roots) when the exception is thrown.

Edit: Assume the Sun JVM - HotSpot is in discussion.

like image 539
Random42 Avatar asked Sep 06 '12 11:09

Random42


People also ask

Will garbage collection guarantee that a program won't run out of memory?

No, garbage collection cannot guarantee that your application will not run out of memory. It will not even guarantee that your application will not run out of memory when memory is available.

When the system is out of memory the garbage collector will run immediately?

The garbage collector runs immediately the system is out of memory before an OutOfMemoryException is thrown by the JVM. Option D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program finishes - this goes against the purpose of the garbage collector.

How does garbage collector prevent Java application going out of memory?

Garbage Collection makes memory management in Java efficient as it removes unreferenced objects from the heap memory without the interference of the programmer. As Garbage collection is automatic and is a part of JVM, no extra efforts are needed from the programmer to reclaim memory or destruct objects.


2 Answers

The garbage collector will usually be run before an OutOfMemoryError is thrown. However you might get an OOME without a GC if you

  • try to create a very large object (e.g. larger than the heap)
  • start a thread and there is not enough virtual memory or resources to start the thread.
  • older versions of Java would throw this error if you reached your maximum direct memory.
like image 40
Peter Lawrey Avatar answered Oct 17 '22 14:10

Peter Lawrey


The Java Machine Specification states in section 6.3 (emphasis mine):

OutOfMemoryError: The Java virtual machine implementation has run out of either virtual or physical memory, and the automatic storage manager was unable to reclaim enough memory to satisfy an object creation request.

So the JVM does give a guarantee that it will try what it can to free up memory through garbage collection before it throws an OOME.

like image 78
assylias Avatar answered Oct 17 '22 14:10

assylias