Sunday, 13 November 2011

Sun Certified Java Programmer (SCJP)-10

Garbage collection


Behavior of the garbage collector


A Java programmer does not have to worry about memory management, because it is automatically taken care of by the garbage collector. The Java virtual machine (JVM) decides when to run the garbage collector. The garbage collector is a low priority thread that runs periodically, releasing memory used by objects that are not needed anymore.

The garbage collection (GC) algorithm varies from one JVM to another. There are different algorithms being used, like reference counting or the mark and sweep algorithm.

Running the garbage collector


The JVM usually runs the garbage collector when the level of available memory is low. However, the garbage collector cannot ensure that there will always be enough memory.

If there is not enough memory even after the garbage collector reclaims memory, the JVM throws an OutOfMemoryError exception. Note that the JVM will definitely run the garbage collector at least once before throwing this exception.

While you can request that the garbage collector run, it is important to note that you can never force this action.

Requesting that the garbage collector run


To request garbage collection, you can call either of the following methods:

System.gc()
Runtime.getRuntime().gc()


1 comment: