Have you ever used PhantomReference in any project?

JavaReference

Java Problem Overview


The only thing I know about PhantomReference is,

  • If you use its get() method, it will always return null and not the object. What's the use of it?
  • By using PhantomReference, you make it sure that the object cannot be resurrected from finalize method.

> But what is the use of this concept/class?
> > Have you ever used this in any of your project or do you have any example where we should use this?

Java Solutions


Solution 1 - Java

I used PhantomReferences in a simplistic, very specialized kind of memory profiler to monitor object creation and destruction. I needed them to keep track of destruction. But the approach is out-dated. (It was written in 2004 targeting J2SE 1.4.) Professional profiling tools are much more powerful and reliable and the newer Java 5 features like JMX or agents and JVMTI can be used for that too.

PhantomReferences (always used together with the Reference queue) are superior to finalize which has some problems and should therefore be avoided. Mainly making objects reachable again. This could be avoided with the finalizer guardian idiom (-> read more in 'Effective Java'). So they are also the new finalize.

Furthermore, PhantomReferences

> allow you to determine exactly when an object was removed from memory. They > are in fact the only way to determine that. This isn't generally that > useful, but might come in handy in certain very specific circumstances > like manipulating large images: if you know for sure that an image should be > garbage collected, you can wait until it actually is before attempting to > load the next image, and therefore make the dreaded OutOfMemoryError less > likely. (Quoted from enicholas.)

And as psd wrote first, Roedy Green has a good summary of references.

Solution 2 - Java

A general diced-up table explanation, from the Java Glossary.

Which of course coincides with the PhantomReference documentation:

> Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

And last but not least, all the gory details (this is a good read): Java Reference Objects (or How I Learned to Stop Worrying and Love OutOfMemoryError).

Happy coding. (But to answer the question, I've only ever used WeakReferences.)

Solution 3 - Java

Great explanation of Phantom Reference usage:

> Phantom references are safe way to know an object has been removed > from memory. For instance, consider an application that deals with > large images. Suppose that we want to load a big image in to memory > when large image is already in memory which is ready for garbage > collected. In such case, we want to wait until the old image is > collected before loading a new one. Here, the phantom reference is > flexible and safely option to choose. The reference of the old image > will be enqueued in the ReferenceQueue once the old image object is > finalized. After receiving that reference, we can load the new image > in to memory.

Solution 4 - Java

I found a practical and useful use case of PhantomReference which is org.apache.commons.io.FileCleaningTracker in commons-io project. FileCleaningTracker will delete the physical file when its marker object is garbage collected.
Something to take note is the Tracker class which extends PhantomReference class.

Solution 5 - Java

THIS SHOULD BE OBSOLETE WITH JAVA 9!
Use java.util.Cleaner instead! (Or sun.misc.Cleaner on older JRE)

Original post:


I found that the use of PhantomReferences has nearly the same amount of pitfalls as finalizer methods (but a fewer problems once you get it right). I have written a small solution (a very small framework to use PhantomReferences) for Java 8. It allows to use lambda expressions as callbacks to be run after the object has been removed. You can register the callbacks for inner resources that should be closed. With this I have found a solution that works for me as it makes it much more practical.

https://github.com/claudemartin/java-cleanup

Here's a small example to show how a callback is registered:

  class Foo implements Cleanup {
    //...  
    public Foo() { 
    //...    
      this.registerCleanup((value) -> {
        try {
          // 'value' is 'this.resource'
          value.close();
        } catch (Exception e) {
          logger.warning("closing resource failed", e);
        }
      }, this.resource);
    }

And then there is the even simpler method for auto-close, doing about the same as the above:

this.registerAutoClose(this.resource);

To answer your questions:

> [ then whats the use of it ]

You can't clean up something that doesn't exist. But it could have had resources that still exist and need to be cleaned up so they can be removed.

> But what is the use of this concept/class?

It's not necessarily to do anything with any effect other than debugging/logging. Or maybe for statistics. I see it more like a notification service from the GC. You could also want to use it to remove aggregated data that becomes irrelevant once the object is removed (but there are probably better solutions for that). Examples often mention database connections to be closed, but I don't see how this is such a good idea as you couldn't work with transactions. An application framework will provide a much better solution for that.

> Have you ever used this in any of your project, or do you have any example where we should use this? Or is this concept made just for interview point of view ;)

I use it mostly just for logging. So I can trace the removed elements and see how GC works and can be tweaked. I wouldn't run any critical code in this way. If something needs to be closed then it should be done in a try-with-resource-statement. And I use it in unit tests, to make sure I don't have any memory leaks. The same way as jontejj does it. But my solution is a bit more general.

Solution 6 - Java

I used a PhantomReference in a unit test to verify that the code under test didn't keep unnessecary references to some object. (Original code)

import static com.google.common.base.Preconditions.checkNotNull;
import static org.fest.assertions.Assertions.assertThat;

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

import com.google.common.testing.GcFinalization;

/**
* Helps to test for memory leaks
*/
public final class MemoryTester
{
private MemoryTester()
{
}

/**
* A simple {@link PhantomReference} that can be used to assert that all references to it is
* gone.
*/
public static final class FinalizationAwareObject extends PhantomReference<Object>
{
private final WeakReference<Object> weakReference;

private FinalizationAwareObject(Object referent, ReferenceQueue<Object> referenceQueue)
{
super(checkNotNull(referent), referenceQueue);
weakReference = new WeakReference<Object>(referent, referenceQueue);
}

/**
* Runs a full {@link System#gc() GC} and asserts that the reference has been released
* afterwards
*/
public void assertThatNoMoreReferencesToReferentIsKept()
{
String leakedObjectDescription = String.valueOf(weakReference.get());
GcFinalization.awaitFullGc();
assertThat(isEnqueued()).as("Object: " + leakedObjectDescription + " was leaked").isTrue();
}
}

/**
* Creates a {@link FinalizationAwareObject} that will know if {@code referenceToKeepTrackOff}
* has been garbage collected. Call
* {@link FinalizationAwareObject#assertThatNoMoreReferencesToReferentIsKept()} when you expect
* all references to {@code referenceToKeepTrackOff} be gone.
*/
public static FinalizationAwareObject createFinalizationAwareObject(Object referenceToKeepTrackOff)
{
return new FinalizationAwareObject(referenceToKeepTrackOff, new ReferenceQueue<Object>());
}
}

And the test:

@Test
public void testThatHoldingOnToAnObjectIsTreatedAsALeak() throws Exception
{
	Object holdMeTight = new String("Hold-me-tight");
	FinalizationAwareObject finalizationAwareObject = MemoryTester.createFinalizationAwareObject(holdMeTight);
	try
	{
	finalizationAwareObject.assertThatNoMoreReferencesToReferentIsKept();
	fail("holdMeTight was held but memory leak tester did not discover it");
	}
	catch(AssertionError expected)
	{
	assertThat(expected).hasMessage("[Object: Hold-me-tight was leaked] expected:<[tru]e> but was:<[fals]e>");
	}
}

Solution 7 - Java

It is common to use WeakReference where PhantomReference is more appropriate. This avoids certain problems of being able to resurrect objects after a WeakReference is cleared/enqueued by the garbage collector. Usually the difference doesn't matter because people are not playing silly buggers.

Using PhantomReference tends to be a bit more intrusive because you can't pretend that the get method works. You can't, for example, write a Phantom[Identity]HashMap.

Solution 8 - Java

I used it in the early days of Android. Back them a BitmapDrawable had an underlying Bitmap that used memory that was not allocated in the Java Heap space, which meant that you were using memory, but the JVM didn't feel the memory pressure. The symptom was the app would crash by running out of memory, but you'd never find that your finalizer was called (or that there hadn't been a garbage collection sweep at all).

So I created a subclass of PhantomReference that had a hard reference to the Bitmap (class variable). The PhantomReference itself pointed to the BitmapDrawable.

When the phantom reference would come off the queue indicating that the BitmapDrawable was no longer reachable, I'd call the release method on the Bitmap which released the memory that was outside of the vm heap space.

It worked great, it more or less completely removed the out of memory failures that occurred because of that weird memory model on early Android.

Android later changed the memory model to load bitmaps into the JVM heap, btw, because you actually want your vm to feel memory pressure if the app is running out of memory. It was definitely a "Black Diamond" situation to have to release the memory like this and I doubt most app developers realized that Garbage Collection wasn't going to help them because the memory was outside the view of the Garbage Collector. They probably just viewed it as an Android bug.

Solution 9 - Java

> if you use its get() method it will always return null, and not the > object. [ then whats the use of it ]

The useful methods to call (rather than get()) would be isEnqueued() or referenceQueue.remove(). You would call these methods to perform some action that needs to take place on the final round of garbage collection of the object.

The first time around is when the object has its finalize() method called, so you could put closing hooks there too. However, as others have stated, there are probably more sure ways of performing clean up or whatever action needs to take place pre and post garbage collection or, more generally, upon end-of-life of the object.

Solution 10 - Java

I found another practical use of PhantomReferences in LeakDetector class of Jetty.

Jetty uses LeakDetector class to detect if the client code acquires a resource but never releases it and the LeakDetector class uses the PhantomReferences for this purpose.

Solution 11 - Java

Here is a generic example of using it: In this case, for some Swing code in a vector editor, where it's easy to create tens of thousands of AffineTransform instances inside the paint loop, when they are easily recycled and reused, and this showed itself to be a significant bottleneck in profiling. I've used the same pattern to reuse CharBuffer instances when processing log files line-by line. Basically the pattern is: You have some data structure which is expensive to create, and it is one you can completely reset the state on, rather than create a new one every time. So, you create a PhantomReference subclass that strongly references the object you want to recycle and reuse, whose referent is a thing that could be referencing the object; to track when it is safe to recycle an object, you either

  1. Return a facade for the object, that implements the same interface or something close enough (e.g. a CharSequence implementation that wraps a CharBuffer), and use that as the referent of your PhantomReference or
  2. Callers pass you a reference to themselves and so you can recycle an object when the caller goes out of scope

In other words, the pattern here you're asking the queue to tell you when every object that could know about some cached thing is gone, so you can make it available for reuse to another caller.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRakesh JuyalView Question on Stackoverflow
Solution 1 - JavaPeter KoflerView Answer on Stackoverflow
Solution 2 - Javauser166390View Answer on Stackoverflow
Solution 3 - JavaSergii ShevchykView Answer on Stackoverflow
Solution 4 - JavaTan Hui OnnView Answer on Stackoverflow
Solution 5 - JavaClaude MartinView Answer on Stackoverflow
Solution 6 - JavajontejjView Answer on Stackoverflow
Solution 7 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 8 - JavaBryant HarrisView Answer on Stackoverflow
Solution 9 - Javauser2066936View Answer on Stackoverflow
Solution 10 - JavaSahil ChhabraView Answer on Stackoverflow
Solution 11 - JavaTim BoudreauView Answer on Stackoverflow