Programming Tutorials

Garbage collection and Finalize() method in Java

By: aathishankaran in Java Tutorials on 2007-03-05  

Garbage collection in Java is the process of freeing up memory that is no longer in use by the program. In Java, garbage collection is done automatically by the JVM. When an object is no longer reachable, it becomes eligible for garbage collection.

The finalize() method is a method that is called by the garbage collector just before an object is about to be garbage collected. The purpose of the finalize() method is to give an object a chance to clean up any resources it has allocated before it is destroyed.

Here's an example of how the finalize() method works:

public class Box {
    private int width;
    private int height;

    public public Box(int width, int height) {
        this.width = width;
        this.height = height;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Box object is being garbage collected.");
    }
}

public class Main {
    public static void main(String[] args) {
        Box box = new Box(10, 20);
        box = null; // make the object eligible for garbage collection
        System.gc(); // call the garbage collector
    }
}

In this example, we define a Box class with a finalize() method that simply prints a message to the console. In the Main class, we create a Box object and then set the object reference to null, which makes the object eligible for garbage collection. We then call the System.gc() method, which suggests to the JVM that it should run the garbage collector. The garbage collector will then call the finalize() method of the Box object before it is destroyed.

It's worth noting that the finalize() method is called by the garbage collector, which means it's not guaranteed to be called at any particular time. In fact, it's possible for the finalize() method to never be called at all. Therefore, the finalize() method should not be relied upon for critical cleanup tasks. Instead, it should be used as a last resort when other cleanup mechanisms are not available.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)