Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to identify that object is collected by garbage collector or not in java?

i have read that object becomes eligible for garbage collection in following cases.

  1. All references of that object explicitly set to null.
  2. Object is created inside a block and reference goes out scope once control exit that block.
  3. Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

But is there anyway to identify that object which is eligible for garbage collection is collected by garbage collector?

like image 868
Dhruv Kapatel Avatar asked Dec 11 '13 19:12

Dhruv Kapatel


1 Answers

You can implement the Object#finalize() method

public class Driver {
    public static void main(String[] args) throws Exception {
        garbage();

        System.gc();
        Thread.sleep(1000);
    }

    public static void garbage() {
        Driver collectMe = new Driver();
    }

    @Override
    protected void finalize() {
        System.out.println(Thread.currentThread().getName() + ": See ya, nerds!");
    }
}

which prints

Finalizer: See ya, nerds!

So you can intercept right before collection. The javadoc states

The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads;

but also

The finalize method is never invoked more than once by a Java virtual machine for any given object.

like image 193
Sotirios Delimanolis Avatar answered Oct 31 '22 22:10

Sotirios Delimanolis