Garbage Collection in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Garbage Collection in Java

Share This

In Java programming language, garbage collection is performed by JVM. JVM determines the objects which are no longer used in a program to free up memory space.

When objects are created using new , there is no delete operation to reclaim memory space. Though in some other object oriented languages like C++, there is a concept of destructor. Even if you set null to an object reference, the memory space is not freed. Thus the process by which JVM finds and reclaims these memory space is known as garbage collection.

JVM performs garbage collection without your intervension and you have no direct control over it.

But, you can implement a finalize method, which will be executed before an object's memory is reclaimed, though this one is rarely used. You should write finalize method with great care as it may craete a scenario where other objects refers to the garbage.

Garbage collector collects only memory, not non-memory resources. If you open a file in your program, you have to close it.

Here, the following program demonstrates garbage collection.

public class ProcessFile { private FileReader fileReader; public ProcessFile(String path) throws FileNotFoundException { fileReader = new FileReader(path); } public synchronized void close() throws IOException { if (fileReader != null) { fileReader.close(); fileReader = null; } } protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } }

As we have discussed that there is no way to free unused objects, but you can call garbage collector explicitly as shown below.

First we are printing available memory in JVM and then garbage collection is performed using gc method of RunTime class, and finally the available memory is printed after garbage collection.


package com.t4b.test; import java.util.*; class GarbageCollection { public static void main(String s[]) throws Exception { Runtime rt = Runtime.getRuntime(); System.out.println("Free memory: " + rt.freeMemory()); rt.gc(); System.out.println("Free memory: " + rt.freeMemory()); } }








Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.