Calling System.gc() requests that garbage collection takes place, and isn't guaranteed. The part about it not being guaranteed is interesting to me: can someone explain the exact process that takes place when you make this call?
The exact process is JVM specific, and is actually an area where a lot of research is taking place. This is possible because the specification is so vague on what actually should happen.
Originally Java had a "stop everything and look at every object to see which ones are still alive". This was 1) slow and 2) stopped everything while this happened.
Today, Sun-based JVM's have several pools of objects as most objects do not live long, so by keeping the separate pools much work can be avoided.
Suns documentation on how to tweak the gc in java 5 is quite instructive on what goes on:
There are no guarantees that a garbage collection will take place, because there are no guarantees that the JVM supports garbage collection (I don't believe it's mentioned in the JLS at all, certainly not in the index).
However, I think this belief that "it's not guaranteed" is a little misplaced. From the Sun API docs:
When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
OK, so maybe it's not guaranteed, but this indicates to me that a normal JVM will actually start a GC cycle when you call this method. Perhaps some JVMs won't, and perhaps some future garbage collector won't, but for now, it does what's advertised.
Of course, that said, there's almost never a reason for application code to call this method. The JVM will collect the garbage when it needs to do so.
The exact process depends on the version and vendor of the JVM.
There are different algorithms - mark and sweep, generational, etc. Usually they run in a parallel threads.
A JVM can have the call to System.gc()
disabled, so that's one good reason is isn't guaranteed. IBM's Java theory and practice: Garbage collection and performance talks more about this, and explains why what seems obvious for helping out the GC can actually hurt performance. It also explains many of the algorithms that are used for implementing GC's.
Sun also has described a variety of their GC implementations in Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning.