开发者

When a PhantomReference/SoftReference/WeakReference is queued, how do you know what it referred to?

开发者 https://www.devze.com 2023-04-12 02:41 出处:网络
I haven\'t used PhantomReferences.There seems to be very few good examples of real-world use. When a phantom shows up in your queue, how do you know which object it is/was?The get() method appears to

I haven't used PhantomReferences. There seems to be very few good examples of real-world use.

When a phantom shows up in your queue, how do you know which object it is/was? The get() method appears to be useless. According to the JavaDoc,

Because the referent of a phantom reference is always inaccessible, this method always returns null.

I think that unless your object is a singleton, you always want to use a subclass of PhantomReference, in which you place whatever mementos you need in order to understand what died.

Is this corre开发者_开发问答ct, or did I miss something?

Is this also true for SoftReferences? For WeakReferences?

Links to relevant examples of usage would be great.


I think that unless your object is a singleton, you always want to use a subclass of PhantomReference, in which you place whatever mementos you need in order to understand what died.

You could also use a Map<Reference<?>, SomeMetadataClassOrInterface> to recover whatever metadata you need. Since ReferenceQueue<T> returns a Reference<T>, you either have to cast it to whatever subclass of PhantomReference you expect, or let a Map<> do it for you.

For what it's worth, it looks like using PhantomReferences puts some burden on you:

Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable.

so you'd have to clear() the references yourself in order for memory to be reclaimed. (why there is usefulness in having to do so vs. letting the JVM do this for you is beyond me)


Your question has caused me to look into it a little more, and I found this very well written explanation and examples of all the reference types. He even talks about some (tenuous) uses of phantom references.

http://weblogs.java.net/blog/2006/05/04/understanding-weak-references

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号