Monday, 20 January 2014

Using Garbage Collection in java

GARBAGE COLLECTION:

In java, garbage means unreferenced objects.The java.lang.System.gc() method runs the garbage collector. Calling this suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.
It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.It is automatically done by the garbage collector so we don't need to make extra efforts.

Declaration:

public static void gc()

This is the declaration for java.lang.System.gc() method


Example for garbage collection in java

import java.util.*;
 class GarbageCollection
{
public static void main(String s[]) throws Exception
 {
 Runtime rs =  Runtime.getRuntime();
 System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
  rs.gc();
 System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
 }
}

This would produce the following results

Free memory in JVM before Garbage Collection=61738736
Free memory in JVM after Garbage Collection =61506664

Obviously the amount of available after garbage collection will be different on your computer. Numbers are not important, what is important is that amount of memory available is more than before. You can use this code in your program or projects which uses large amount of memory or where frequently new objects are created but are required for a short span of time.

 





No comments:

Post a Comment