I was doing some exercises of Bates & Sierrra book and I came up that question.
Create a class that has a method such that the first time the garbage collector attempts to collect a given instance, this method will keep garbage collector from collecting that instance at that point.
Could it be an option the method finalize(), and pass a reference to the object to another?
I think so. In the finalize method of the object, you can try to assign the object instance to a static variable and see.
This is one of the many examples. It may not be a perfect example though.
But there is no guarantee that finalize method will run. If the garbage collector never GC the object, the finalized method won't be called.
If the finalize() method is called and the object is saved the object could still be GC'ed later on because the finalize() method is only called once on each object. Thus the next time the JVM tries to GC this object it will not run the finalize() method and the object will be destroyed.
So the poor little object only has one chance to live, the second time certain death.
Alex Theedom - Senior Java EE Developer (OCPJP/OCPJWCD)
Is there a way to check i out? I mean, how can I know how many objects are eligible?
Joined: Nov 01, 2011
When we say an object is eligible for GC, it means it is only possible to be GC. But there is no guarantee that it will be GCed.
When an object has no variable referring to it, it will be eligible for GC.
The object is just a like a piece of trash inside a trash can. The trash will be ready to be picked up by the truck. But there is no guarantee that the truck will come by to pick up the trash.
For more information, you can check on some other posts titled "Garbage Collection" and "Garbage Collection 2".
While this is very interesting at a theoretical level -- this is, of course, completely not practical. After all, if an object is still needed, why would an application make it not reachable? And even if it is deemed not needed (and hence, made not reachable), and then deemed needed at a later time, what kind of need can actually wait for a GC cycle for it to be recovered?