Reputation: 23
So the garbage collector does not deletes object immediately, is there any way to set the reference to the object which is already eligible for GC?
Object o = new Object();
o = null; // above object is eligible for GC
// now can we retrieve the above object? as it is not destroyed by GC
Upvotes: 0
Views: 61
Reputation: 49616
Object o = new Object();
WeakReference<Object> weakReference = new WeakReference<>(o);
o = null;
o = weakReference.get();
You can weakly refer to the object the references of which you want to nullify. It will be available (more precisely, weakly reachable) via weakReference.get()
unless it's been cleared by the GC.
Of course, it becomes fully unreachable if no references of any kind (strong/soft/weak/phantom) relate to it.
Upvotes: 1