Junior — Middle
What is the use of PhantomReference in memory management and how does it work in Java?
sobes.tech AI
Answer from AI
PhantomReference in Java is used for more fine-grained memory management and resource cleanup after an object becomes unreachable, but before the memory is actually reclaimed by the garbage collector.
How it works:
- PhantomReference refers to an object but does not prevent its collection.
- Once the object becomes unreachable, the PhantomReference is placed in a ReferenceQueue.
- The program can monitor this queue and perform additional actions (such as releasing native resources) when the object is ready to be collected.
Unlike SoftReference and WeakReference, get() on a PhantomReference always returns null, so it is not used to access the object, only to notify when it has been collected.
An example use case is releasing resources associated with an object that are not managed by the JVM, such as file descriptors or native memory.