Garbage Collection

The Java runtime system normally includes a garbage collector.[6] Some of the commercial profilers provide statistics showing what the garbage collector is doing. You can also use the -verbosegc option with the VM. This option prints out time and space values for objects reclaimed and space recycled as the reclamations occur. The printout includes explicit synchronous calls to the garbage collector (using System.gc( )) as well as asynchronous executions of the garbage collector, as occurs in normal operation when free memory available to the VM gets low.

Note

System.gc( ) does not necessarily force a synchronous garbage collection. Instead, the gc( ) call is really a hint to the runtime that now is a good time to run the garbage collector. The runtime decides whether to execute the garbage collection at that time and what type of garbage collection to run.

It is worth looking at some output from running with -verbosegc. The following code fragment creates lots of objects to force the garbage collector to work, and also includes some synchronous calls to the garbage collector:

package tuning.gc; public class Test { public static void main(String[] args) { int SIZE = 4000; StringBuffer s; java.util.Vector v; //Create some objects so that the garbage collector //has something to do for (int i = 0; i < SIZE; i++) { s = new StringBuffer(50); v = new java.util.Vector(30); s.append(i).append(i+1).append(i+2).append(i+3); } s = null; v = null; System.out.println("Starting ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.