What is the purpose of garbage collection in Java?

The purpose of garbage collection in Java is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused later.

The garbage collection (actually collector) is a program that runs on the JVM (Java Virtual Machine), which gets rid of objects that are no longer used by Java applications. It’s a form of automatic memory management process.

When a Java application is running, required new objects are getting created, such as, Strings or Files but after a certain time, those objects are not used in the application.

Let’s take an example with the following code snippets:

for(File file: files) {
   String filePath = f.getPath();

In the above code the variable String filePath gets created on each iteration of the for loop.

Therefore at each iteration a memory is being allocated for the above String object.

So if we look at the code carefully, we can see that once a single iteration is executed, in the next iteration, the String object that was created in the previous iteration is not being used anymore and that object is now considered as garbage collected.

At the end, we will start getting a lot of such garbage and memory will be used for objects which are not being used anymore. If this keeps going on, eventually the JVM will run out of memory or space to make new objects.

That’s where the garbage collector steps in and it will look for objects which are not being used anymore, and gets rid of them, freeing up the memory so that other new objects can use that free space or memory.

Therefore, a Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory.

Every class inherits finalize() method from java.lang.Object, the finalize() method is called by the garbage collector when it determines no more reference to the object exists.

In Java, it is a good idea to explicitly assign null value into a variable when the variable is no longer in use.

In Java, calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Garbage collection is an automatic process and cannot be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().

Automatic memory management schemes like garbage collection makes the programmer’s life easier as the programmer does not need to worry about memory management issues and the programmer can focus more on developing the application’s business.

Thanks for reading.

Leave a Reply

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