The System.gc() method

Although garbage collection is automatic in Java, you can make explicit calls to the java.lang.System.gc() method to aid in the debugging process. This method does not take any parameters and does not return any value. It is an explicit call that runs Java's garbage collector. Here is a sample implementation:

System.gc();
System.out.println("Garbage collected and unused memory has been deallocated.");

Let's look at a more in-depth example. In the following code, we start by creating an instance of Runtime, using Runtime myRuntime = Runtime.getRuntime();which returns a singleton. This gives us access to the JVM. After printing some header information and initial memory stats, we create ArrayList with a size of 300000. Then, we create a loop that generates 100000 array list objects. Lastly, we provide output in three passes, asking the JVM to invoke the garbage collector with 1 second pauses in between. Here is the source code:

package MyGarbageCollectionSuite;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class GCVerificationTest {
public static void main(String[] args) throws InterruptedException {
// Obtain a Runtime instance (to communicate with the JVM)
Runtime myRuntime = Runtime.getRuntime();

// Set header information and output initial memory stats
System.out.println("Garbage Collection Verification Test");
System.out.println("-----------------------------------------------
-----------");
System.out.println("Initial JVM Memory: " + myRuntime.totalMemory()
+
" Free Memory: " + myRuntime.freeMemory());

// Use a bunch of memory
ArrayList<Integer> AccountNumbers = new ArrayList<>(300000);
for (int i = 0; i < 100000; i++) {
AccountNumbers = new ArrayList<>(3000);
AccountNumbers = null;
}

// Provide update with with three passes
for (int i = 0; i < 3; i++) {
System.out.println("--------------------------------------");
System.out.println("Free Memory before collection number " +
(i+1) + ": " + myRuntime.freeMemory());
System.gc();
System.out.println("Free Memory after collection number " +
(i+1) + ": " + myRuntime.freeMemory());
TimeUnit.SECONDS.sleep(1); // delay thread 5 second
}
}
}

As you can see from the following output, the garbage collector did not reallocate all of the garbage during the first or even the second pass:

Garbage collection verification test

There is an alternative to using the System.gc() method to invoke the garbage collector. In our example, we could have used myRuntime.gc(), our earlier singleton example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset