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 the 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 an ArrayList with a size ...

Get Java 9: Building Robust Modular Applications 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.