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.");
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?