Java Garbage Collection Explained

If you have developed code in C or C++, you know the programmer was completely responsible for the memory allocation and de-allocation of objects. Ultimately this led to some very frustrating to find memory leaks.

Thankfully in Java you do not have to worry about allocating and freeing objects because the Garbage Collector is responsible for this. The Java Garbage Collector (GC) runs as a daemon thread all the time and destroys objects that are no longer reachable or just unused in memory.

Can You Force Garbage Collector?

If you’re in an interview or taking a Java certification exam, this is where you would answer no. While you can call System.gc() within your application, there is no such guarantee the garbage collector will run and cleanup objects.


Unreachable Object Sample Code

In the sample code below, we create a String Array with five elements. The jcdStringArray object is reachable and not subject for cleanup by the garbage collector. As soon as we set jcdStringArray to null, it is no longer reachable and the garbage collector may come by and clean it from memory.

        //Define a String Array
		String[] jcdStringArray = new String[5];
		
		//jcdStringArray is Reachable
		
		jcdStringArray = null;
		
		//jcdStringArray is No Longer Reachable


Request Garbage Collection Sample Code

We can request the garbage collector to run in one of two ways. Calling System.gc() or Runtime.getRuntime.gc() will request the garbage collector to run, but as stated earlier this is only a request which you can’t force. Both of these calling methods are essentially doing the same thing.

        //Define a String Array
		String[] jcdStringArray = new String[5];
		
		//jcdStringArray is Reachable
		
		jcdStringArray = null;
		
		//jcdStringArray is No Longer Reachable
		
		//Request the Garbage Collector (1)
		System.gc();
		
		//Request the Garbage Collector (2)
		Runtime.getRuntime().gc();


Finalize Method

Before the GC destroys an object, it will call the finalize() method. The finalize() method, which is inherited from the Object class, performs various cleanup activities that you don’t need to worry about. After finalize(), the object in question is destroyed from memory.


Add a Comment

Your email address will not be published. Required fields are marked *