8

I read many articles, but I don't understand - where do I need to use Weak and Phantom references in practice? Soft references - is a good choice for cache, as I understand. But weak and phantom, I don't know when to use. Please provide examples of real tasks where we need to use them.

1
  • 1
    You don't need to use phantom references. These are for internal use. Youc an use weak references where ever you use soft references, except they have a shorter life. You can use weak references when they are only meaningful if another object also has a reference. e.g. listeners. Jul 9, 2012 at 14:59

4 Answers 4

8

You can use weak references for cache, simply like soft references as you said.

What good are PhantomReferences? I'm only aware of two serious cases for them: first, they 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.

Second, PhantomReferences avoid a fundamental problem with finalization: finalize() methods can "resurrect" objects by creating new strong references to them. So what, you say? Well, the problem is that an object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected. When the first cycle determines that it is garbage, it becomes eligible for finalization. Because of the (slim, but unfortunately real) possibility that the object was "resurrected" during finalization, the garbage collector has to run again before the object can actually be removed. And because finalization might not have happened in a timely fashion, an arbitrary number of garbage collection cycles might have happened while the object was waiting for finalization. This can mean serious delays in actually cleaning up garbage objects, and is why you can get OutOfMemoryErrors even when most of the heap is garbage.

for more details see this page : http://weblogs.java.net/blog/2006/05/04/understanding-weak-references

3
  • 4
    Weak refs are absolutely useless for caching. Jul 9, 2012 at 16:04
  • 1
    The probability of a finalizable object getting resurrected isn't "slim"--it's 100%; a finalizable object which would cease to exist but for the existence of a finalize method will have a strong reference to it placed on the stack when its finalizer starts running. The object can't be deleted until that reference (and all other rooted reference) have ceased to exist.
    – supercat
    Dec 8, 2014 at 22:15
  • According to the OoME JavaDoc Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. So it doesn't matter if the large image is in memory or not, because if it is it will try to throw it out, before failing. Otherwise, you should know if you are holding any remaining references to it.
    – Sled
    Mar 28, 2019 at 15:34
5

Basically, you'll use a Weak ref when you want to associate some additional data with objects whose source code is not under your control. By using a weak ref you'll couple the lifecycle of your meta-objects to the lifecycle of the primary objects.

The main use case for phantom refs is implementing your own finalizer thread without the dangers associated with the default mechanism, which is forced to make the reference to the supposedly unreachable object accessible to the finalization code.

Soft refs are primarily for caching, but, as said in another post here, they can give quite disastrous effects in practice, undermining the very point of caching. A major GC (the one that will clear your Soft refs) usually doesn't happen until the pressure on your app's performance rises. This is the time when you need your cache the most, and the time you are most likely to lose it – all at once.

3
  • According the OP, He want to know when to use Phantom references vs Weak References....Your reply doesn't answer his original question completely May 11, 2017 at 15:01
  • No, you are misrepresenting the question, which is when to use weak and phantom references. It is not about how to choose between them, but when to use any of them. So even if this answer didn't deal with phantom refs (as of the time of your comment; it does deal with it now), everything it states is both on-topic and correct. May 11, 2017 at 15:08
  • I agree, the new answer covers the topic well May 12, 2017 at 14:52
3

I think this post answers your question pretty well.

What is the difference between a soft reference and a weak reference in Java?

Basically a soft reference is slightly stronger than a weak reference. A weak reference will be discarded on the next GC cycle, while a soft reference will stay in memory until there is memory pressure and the JVM wants to reclaim as much as it can.

You should think about how important is it to your program that the reference you have is still valid. For something that is extremely cheap to recreate a reference to, I would lean towards a WeakReference, but if it's a value from a DB you might lean towards the soft reference since you'd rather not rerun a query unless you really need to.

2
  • Thank you. But I understand difference between this references types. I did not understand in what specific task can apply them. Jul 9, 2012 at 15:00
  • I added my view of when to use a Weak vs. Soft reference
    – jjathman
    Jul 9, 2012 at 15:30
0

SoftReference objects are not collected until all WeakReference objects have been garbage collected.

So put less important objects in WeakReference objects, and use SoftReference objects to hold more important object.

Given those facts you should use the good Reference objects depending on you need in term of garbage collection. The WeakReference are collected first, then the SoftReference and finally the PhantomReferences.

The documentation says :

  • Soft references are for implementing memory-sensitive caches
  • Weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed

By the way, in some case, for cache purpose, it can be a good idea to use WeakReference instead of SoftReference because the cache can be heavy in memory, and so, need to be cleaned.

For PhantomReference, the use is different. They are for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

This article elaborate a bit on what can be the use of PhantomReference.

16
  • 1
    you are pretty much right about weak and soft references. you are wrong about PhantomReferences. PhantomReferences are only useful as a replacement for the finalize method (aka resource cleanup). they have nothing to do with caching or when an object will get gc'ed.
    – jtahlborn
    Jul 9, 2012 at 15:19
  • @jtahlborn First I've never stated that PhantomReferences are for caching (I'm speaking of WeakReference in relation with what is stated in OP). Then I know it's a kind a replacement for finalize() but for the gc order I read it in Java Perf Tuning, and this link seems to say the same thing : docs.oracle.com/javase/7/docs/api/java/lang/ref/… Jul 9, 2012 at 15:33
  • 1
    Weak refs don't delay anything---they get cleared as soon as there is no "normal" reference to the referent (it's not strongly reachable). That's why they fail as caches -- object will get into the young gen and can get cleared in a matter of seconds, with free heap still in plentiful supply. Jul 9, 2012 at 16:41
  • 1
    Consider this statement: You don't come of age until you have lived out your teens'. Do the teens delay your coming of age? Jul 9, 2012 at 18:07
  • 1
    A final remark: most of the discussion about which ref is better for caching is just armchair talk since in a real project you'd never attempt to implement a cache from scratch: you'd use a battle-proven implementation such as ehcache. Good caching is chock-full of subtleties you just don't want to reinvent yourself and the lifecycle of objects on the heap is by no means dedicated to providing good cache performance. Modern caches don't even use the heap for caching, but off-heap storage, because they want to take full control over the lifecycle of cached objects. Jul 9, 2012 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.