ReferenceQueue

Check when an object is no longer referenced

In this example we shall show you how to check when an object is no longer referenced. To check when an object is no longer referenced one should perform the following steps:

  • 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 new WeakReference that refers to the given object and is registered with this.
  • 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,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

public class CheckWhenAnObjectIsNoLongerReferenced {
	
	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 weak reference that refers to the given object and is registered with this queue.
		WeakReference<Object> wr = new WeakReference<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 no longer referenced.");
		
  }
		
  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 no longer referenced.

 
This was an example of how to check when an object is no longer referenced in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button