views:

211

answers:

3

From questions posted here and an old one of mine I have created the impression that you cannot explicitly run the Java Garbage Collector whenever you please.

If you call it, you simply instruct the system to call it whenever it can or thinks is appropriate.

But in eclipse, if you press the "Run Garbage Collector" button you see an immediate reduction in memory usage. How is that possible? Is eclipse using a different Garbage Collector, does it have access to some secret API that we don't or is my conception of how the GC works wrong?

+3  A: 

You can't tell the GC to run, but you can ask it to, using System.gc().

I suspect Eclipse just calls that, and much of the time, the GC decides to do something.

skaffman
+6  A: 

A "normal" Java program cannot force the garbage collector to run. However, using the Java Virtual Machine Tool Interface (JVMTI, an API for connecting for example debuggers to a JVM) you can force garbage collection.

I don't know if Eclipse simply calls System.gc() (which does not force garbage collection) or if it uses the JVMTI API to really force GC to run.

With JVisualVM (included with Sun JDK 6) you can connect to other running Java processes and press a button to run the garbage collector in those processes.

Jesper
+2  A: 

Eclipse calls System.gc(). System.gc() does not force garbage collection, it merely instructs the JVM to give it a try. The JVM is free to ignore it. However, in practice, the default behaviour of Sun's JVM is to run the GC when System.gc() is called.

Please note the following:

  • Sun's JVM can be launched with the -XX:-DisableExplicitGC command-line flag. With this flag, System.gc() becomes a no-operation. The VM will still operate the GC when appropriate, but it will simply ignore any explicit call to System.gc().

  • Forcing the GC to run, regardless of how you do it, is rarely a good idea. The GC is optimized with regards to some heuristic approximations of the running application code (most of which dealing with the complex but crucial matter of cache locality), and explicit calls to the GC are not part of those heuristics. Compulsive GC-running usually turns out to be an elaborate way to slow things down.

  • Maybe I should call it Oracle's JVM ? Oracle bought Sun and all the Java pages now have the Oracle logo everywhere.

Thomas Pornin