ReferenceQueue
Check when an object will be reclaimed
This is an example of how to check when an object will be reclaimed. Checking when an object will be reclaimed implies that you should:
- Create a new Object.
- Create a new ReferenceQueue, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected.
- Create a new PhantomReference that refers to the given object and is registered with this queue.
- Create a Runnable that runs GC to collect the object.
- Start a new Thread, using the runnable that will remove all references of object.
- Wait for all the references to the object to be removed.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; public class CheckWhenAnObjectWillBeReclaimed { private static Object object; public static void main(String[] args) { object = new Object(); // Reference queue, to which registered reference objects are appended by the // garbage collector after the appropriate reachability changes are detected. ReferenceQueue<Object> rq = new ReferenceQueue<Object>(); // Create a new phantom reference that refers to the given object and is registered with this queue. PhantomReference<Object> wr = new PhantomReference<Object>(object, rq); // start a new thread that will remove all references of object new Thread(runnable).start(); // wait for all the references to the object to be removed try { while (true) { Reference<?> r = rq.remove(); if (r == wr) { System.out.println("Object is about to be reclaimed." + "We clear the referent so that it can be reclaimed."); r.clear(); } break; } } catch (InterruptedException e) { e.printStackTrace(); } } private static Runnable runnable = new Runnable() { @Override public void run() { try { Thread.sleep(1000); System.out.println("Setting object to null"); object = null; System.out.println("Running Garbage Collection..."); Runtime.getRuntime().gc(); // run GC to collect the object } catch (Exception e) { e.printStackTrace(); } } }; }
Output:
Setting object to null
Running Garbage Collection...
Object is about to be reclaimed. Clear the referent so that it can be reclaimed.
This was an example of how to check when an object will be reclaimed in Java.