How do you use ReferenceQueue with a simple code example?

The ReferenceQueue in Java is a mechanism that allows you to track when a reference object has been cleared by the garbage collector. This is particularly useful when you are working with Reference or WeakReference objects and need to perform some cleanup or actions when they are no longer reachable.

In this example, we create a `WeakReference` to an object, and we use a `ReferenceQueue` to be notified when the `WeakReference` is cleared. When the garbage collector runs and clears the reference, we can take action based on that.

import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; public class Main { static class MyObject { String name; MyObject(String name) { this.name = name; } @Override protected void finalize() throws Throwable { System.out.println(name + " is being garbage collected."); } } public static void main(String[] args) throws InterruptedException { ReferenceQueue referenceQueue = new ReferenceQueue<>(); MyObject myObject = new MyObject("MyWeakObject"); WeakReference weakReference = new WeakReference<>(myObject, referenceQueue); myObject = null; // Remove strong reference System.gc(); // Suggest the JVM to run the garbage collector // Wait for the ReferenceQueue to receive notification WeakReference clearedRef = (WeakReference) referenceQueue.remove(); System.out.println("Weak reference cleared: " + clearedRef.get() + " has been GC'd."); } }

Java ReferenceQueue WeakReference Garbage Collection Java Example