Understaning weak reference in Java

Source: Internet
Author: User

From http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

 

Some time ago I was interviewing candidates for a senior Java
Engineer position. Among the specified questions I asked was "what can you
Tell me about weak references? "I wasn' t expecting a detailed technical
Treatise on the subject. I wowould probably have been satisfied
"Umm... don't they have something to do with garbage collection? "I was
Instead surprised to find that out of twenty-odd engineers, all of whom
Had at least five years of Java experience and good qualifications,
OnlyTwo
Of them even knew that weak references existed, and only
One of those two had actual useful knowledge about them. I even
Explained a bit about them, to see if I got an "oh yeah" from anybody --
Nope. I'm not sure why this knowledge is (evidently) uncommon, as weak
References are a massively useful feature which have been around since
Java 1.2 was released, over seven years ago.

Now, I'm not suggesting you need to be a weak reference expert
Qualify as a decent Java engineer. But I humbly submit that you showould
At leastKnow what they are
-- Otherwise how will you know when
You shoshould be using them? Since they seem to be a little-known feature,
Here is a brief overview of what weak references are, how to use them,
And when to use them.

Strong references

First I need to start with a refresher onStrong references
. A strong reference is an ordinary Java reference, the kind you use every day. For example, the Code:

 

StringBuffer buffer = new StringBuffer();

Creates a newStringBuffer()
And stores a strong reference to it in the Variablebuffer
.
Yes, yes, this is kiddie stuff, but bear with me. The important part
About strong references -- the part that makes them "strong" -- is how
They interact with the garbage collector. Specifically, if an object is
Reachable via a chain of strong references (strongly reachable), it is
Not eligible for garbage collection. As you don't want the garbage
Collector destroying objects you're working on, this is normally exactly
What you want.

When strong references are too strong

It's not uncommon for an application to use classes that it can't reasonably extend. The class might simply be markedfinal
,
Or it cocould be something more complicated, such as an interface
Returned by a factory method backed by an unknown (and possibly even
Unknowable) number of concrete implementations. Suppose you have to use
A ClassWidget
And, for whatever reason, it isn' t possible or practical to extendWidget
To add new functionality.

What happens when you need to keep track of extra information about
The object? In this case, suppose we find ourselves needing to keep
Track of eachWidget's
Serial number, butWidget
Class doesn' t actually have a serial number Property -- and becauseWidget
Isn't extensible, we can't add one. No problem at all, that's whatHashMaps
Are:

 

serialNumberMap.put(widget, widgetSerialNumber);

This might look okay on the surface, but the strong referencewidget
Will almost certainly cause problems. We have to know (with 100% certainty) when a participant ularWidget's
Serial number is no longer needed, so we can remove its entry from
Map. Otherwise we're re going to have a memory leak (if we don't removeWidgets
When we shoshould) or we're re going to inexplicably find ourselves missing serial numbers (if we removeWidgets
That we're re still using). If these problems sound familiar, they
Shocould: they are exactly the problems that users
Non-garbage-collected ages face when trying to manage memory, and
We're not supposed to have to worry about this in a more civilized
Language like Java.

Another common problem with strong references is caching, particle
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
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 shoshould 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 (just as above) 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. Once again you are forced
Duplicate the behavior of the garbage collector and manually determine
Whether or not an object shocould be in memory.

Weak references

AWeak 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
Weak reference like this:

 

WeakReference<Widget> weakWidget = new WeakReference<Widget>(widget);

And then elsewhere in the code you can useweakWidget.get()
To get the actualWidget
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) thatweakWidget.get()
Suddenly starts returningnull
.

To solve the "widget serial number" problem above, the easiest thing to do is use the built-inWeakHashMap
Class.WeakHashMap
Works exactly likeHashMap
, Keys T that the keys (Not
The values !) Are referred to using weak references. IfWeakHashMap
Key becomes garbage, its entry is removed automatically. This avoids
The pitfalls I described and requires no changes other than the switch
FromHashMap
ToWeakHashMap
. If you're following the standard convention of referring to your maps viaMap
Interface, no other code needs to even be aware of the change.

Reference queues

OnceWeakReference
Starts returningnull
, The object it pointed to has become garbage andWeakReference
Object is pretty much useless. This generally means that some sort of cleanup is required;WeakHashMap
, For example, has to remove such defunct entries to avoid holding onto an ever-increasing number of deadWeakReferences
.

TheReferenceQueue
Class makes it easy to keep track of dead references. If you passReferenceQueue
Into a weak reference's constructor, the reference object will be
Automatically inserted into the reference queue when the object to which
It pointed becomes garbage. You can then, at some regular interval,
ProcessReferenceQueue
And perform whatever cleanup is needed for dead references.

Different degrees of weakness

Up to this point I 've just been referring to "weak references",
There are actually four different degrees of reference strength: strong,
Soft, weak, and phantom, in order from strongest to weakest. We 've
Already discussed strong and weak references, so let's take a look
The other two.

Soft references

ASoft reference
Is exactly like a weak reference, doesn t that
It is less eager to throw away the object to which it refers.
Object which is only weakly reachable (the strongest references to it
AreWeakReferences
) 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'tRequired
To behave any differentlyWeakReferences
,
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
Objects are (a strongly reachable object willNever
Be removed from the cache) and how badly it needs the memory they are consuming.

Phantom references

APhantom reference
Is quite different than eitherSoftReference
OrWeakReference
. Its grip on its object is so tenuous that you can't even retrieve the object -- itsget()
Method always returnsnull
. The only use for such a reference is keeping track of when it gets enqueued intoReferenceQueue
, As at that point you know the object to which it pointed is dead. How is that different fromWeakReference
, Though?

The difference is in exactly when the enqueuing happens.WeakReferences
Are enqueued as soon as the object to which they point becomes weakly reachable. This isBefore
Finalization or garbage collection has actually happened; in theory the object cocould even be "resurrected" by an unorthodoxfinalize()
Method, butWeakReference
Wocould remain dead.PhantomReferences
Are enqueued only when the object is physically removed from memory, andget()
Method always returnsnull
Specifically to prevent you from being able to "resurrect" an almost-dead object.

What good arePhantomReferences
? 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 factOnly
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 shocould be garbage collected,
You can wait until it actually is before attempting to load the next
Image, and therefore make the dreadedOutOfMemoryError
Less likely.

Second,PhantomReferences
Avoid a fundamental problem with finalization:finalize()
Methods can "resurrect" objects by creating new strong references
Them. So what, you say? Well, the problem is that an object which
Overridesfinalize()
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,
Unfortunately real) possibility that the object was "resurrected"
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
Finalization. This can mean serious delays in actually cleaning up
Garbage objects, and is why you can getOutOfMemoryErrors
Even when most of the heap is garbage.

WithPhantomReference
, This situation is impossible -- whenPhantomReference
Is enqueued, there is absolutely no way to get a pointer to
Now-dead object (which is good, because it isn't in memory any longer ).
BecausePhantomReference
Cannot be used to resurrect
Object, the object can be instantly cleaned up during the first garbage
Collection cycle in which it is found to be phantomly reachable. You
Can then dispose whatever resources you need to at your convenience.

Arguably,finalize()
Method shoshould never have been provided in the first place.PhantomReferences
Are definitely safer and more efficient to use, and eliminatingfinalize()
Wocould have made parts of the VM considerably simpler. But, they're also more work to implement, So I confess to still usingfinalize()
Most of the time. The good news is that at least you have a choice.

Conclusion

I'm sure some of you are grumbling by now, as I'm talking about
API which is nearly a decade old and haven'tsaid anything which hasn' t
Been said before. While that's certainly true, in my experience success
Java programmers Really don't know very much (if anything) about weak
References, and I felt that a refresher course was needed. Hopefully
You at least learnedLittle
Something from this review.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.