What's the Difference Between Softreference and Weakreference in Java

What's the difference between SoftReference and WeakReference in Java?

From Understanding Weak References, by Ethan Nicholas:

Weak references

A weak reference, simply put, is a
reference that isn't strong enough to
force an object to remain in memory.
Weak references allow you to leverage
the garbage collector's ability to
determine reachability for you, so you
don't have to do it yourself. You
create a weak reference like this:

WeakReference weakWidget = new WeakReference(widget);

and then
elsewhere in the code you can use
weakWidget.get() to get the actual
Widget object. Of course the weak
reference isn't strong enough to
prevent garbage collection, so you may
find (if there are no strong
references to the widget) that
weakWidget.get() suddenly starts
returning null.

...

Soft references

A soft reference is exactly like a
weak reference, except that it is less
eager to throw away the object to
which it refers. An object which is
only weakly reachable (the strongest
references to it are WeakReferences)
will be discarded at the next garbage
collection cycle, but an object which
is softly reachable will generally
stick around for a while.

SoftReferences aren't required to
behave any differently than
WeakReferences, but in practice softly
reachable objects are generally
retained as long as memory is in
plentiful supply. This makes them an
excellent foundation for a cache, such
as the image cache described above,
since you can let the garbage
collector worry about both how
reachable the objects are (a strongly
reachable object will never be removed
from the cache) and how badly it needs
the memory they are consuming.

And Peter Kessler added in a comment:

The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.

Can someone explain the difference between Strong, Soft, Weak and Phantom references and the usage of it?

Another good article on the topic:

Java Reference Objects or How I Learned to Stop Worrying and Love OutOfMemoryError, with nice diagrams

http://www.kdgregory.com/images/java.refobj/object_life_cycle_with_refobj.gif

Extract:

As you might guess, adding three new optional states to the object life-cycle diagram makes for a mess.

Although the documentation indicates a logical progression from strongly reachable through soft, weak, and phantom, to reclaimed, the actual progression depends on what reference objects your program creates.

If you create a WeakReference but don't create a SoftReference, then an object progresses directly from strongly-reachable to weakly-reachable to finalized to collected. object life-cycle, with reference objects

It's also important to remember that not all objects are attached to reference objects — in fact, very few of them should be.

A reference object is a layer of indirection: you go through the reference object to reach the referred object, and clearly you don't want that layer of indirection throughout your code.

Most programs, in fact, will use reference objects to access a relatively small number of the objects that the program creates.

References and Referents

A reference object provides a layer of indirection between your program code and some other object, called the referent.

Each reference object is constructed around its referent, and provides a get() method to access the referent. Once you create a reference, you cannot change its referent. Once the referent has been collected, the get() method returns null. relationships between application code, soft/weak reference, and referent

alt text


Even more examples: Java Programming: References' Package

alt text http://www.pabrantes.net/blog/space/start/2007-09-16/1/referenceTypes.png

  • Case 1: This is the regular case where Object is said to be strongly reachable.

  • Case 2: There are two paths to Object, so the strongest one is chosen, which is the one with the strong reference hence the object is strongly reachable.

  • Case 3: Once again there are two paths to the Object, the strongest one is the Weak Reference (since the other one is a Phantom Reference), so the object is said to be weakly reachable.

  • Case 4: There is only one path and the weakest link is a weak reference, so the object is weakly reachable.

  • Case 5: Only one path and the weakest link is the phantom reference hence the object is phantomly reachable.

  • Case 6: There are now two paths and the strongest path is the one with a soft reference, so the object is now said to be softly reachable.

When to use Weak and Phantom references in Java

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

When would you use a WeakHashMap or a WeakReference?

One problem with strong references is
caching, particular with very large
structures like images. Suppose you
have an application which has to work
with user-supplied images, like the
web site design tool I work on.
Naturally you want to cache these
images, because loading them from disk
is very expensive and you want to
avoid the possibility of having two
copies of the (potentially gigantic)
image in memory at once.

Because an image cache is supposed to
prevent us from reloading images when
we don't absolutely need to, you will
quickly realize that the cache should
always contain a reference to any
image which is already in memory. With
ordinary strong references, though,
that reference itself will force the
image to remain in memory, which
requires you to somehow determine when
the image is no longer needed in
memory and remove it from the cache,
so that it becomes eligible for
garbage collection. You are forced to
duplicate the behavior of the garbage
collector and manually determine
whether or not an object should be in
memory.

Understanding Weak References, Ethan Nicholas



Related Topics



Leave a reply



Submit