i have read that object becomes eligible for garbage collection in following cases.
But is there anyway to identify that object which is eligible for garbage collection is collected by garbage collector?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With