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.
A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.
An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable. So in brief: Soft references try to keep the reference. Weak references don't try to keep the reference. Phantom references don't free the reference until cleared.
To create a Phantom Reference Object, we must explicitly specify this to the JVM. Phantom Reference Objects are created as phantom reference object is eligible for garbage collection, but it is not collected instantly. Instead, it is pushed into a ReferenceQueue so that all such enqueued references can be cleared.
I used PhantomReference
s 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.
PhantomReference
s (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, PhantomReference
s
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.
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.)
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.
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.
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.
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>");
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With