Witscale Test Center

6.7 Requesting a garbage collection


6.7 Requesting a garbage collection

We saw earlier that we do not have any control over exactly when the garbage collector will run. Moreover you can not force garbage collection. Java however provides you with facility to request the JVM to perform garbage collection.  For instance, if you are about to do some memory-intense operation, you probably want to have as much memory as possible. In such situation, you can request garbage collection. When you make such request, the chances that garbage collection will occur in near future increases. But bear one thing in mind, you are only making a request and JVM does not guarantee that it will comply with your request.

The class java.lang.Runtime allows any java application to interact with its runtime environment (JVM). You can request garbage collection routines by calling the methods of this class. It is a singleton class, you can request the garbage collection by first getting its instance and then calling its instance method gc() like this:

 

Runtime runtime = Runtime.getRuntime();

runtime.gc();

 

Alternatively the java.lang.System has a utility method which essentially does the same thing. So you can also request garbage collection as:

 

System.gc();

 

After you request, the JVM will probably make an effort to run garbage collection. In theory, you should have as much free memory as possible after this method runs. However in reality you can never be sure.  The garbage collector may not run at all or even if it runs, some other program may immediately allocate the freed memory for its objects. So the bottom line is you cannot be sure that you will have more memory, but you can increase your chances by requesting garbage collection.