Java Reference
In-Depth Information
Weak references
Weak references should be used when the referent in question will be used by several threads
simultaneously. Otherwise, the weak reference is too likely to be reclaimed by the garbage
collector: objects that are only weakly referenced are reclaimed at every GC cycle.
What that means is that weak references never get into the state shown (for soft references)
in Figure 7-8 . When the strong references are removed, the weak reference is immediately
freed. Hence the program state moves directly from Figure 7-7 to Figure 7-9 .
The interesting effect here, though, is where the weak reference ends up in the heap. Refer-
ence objects are just like other Java objects: they are created in the young generation and
eventually promoted to the old generation. If the referent of the weak reference is freed while
the weak reference itself is still in the young generation, the weak reference will be freed
quickly (at the next minor GC). (This assumes that the reference queue is quickly processed
for the object in question.) If the referent remains around long enough for the weak reference
to be promoted into the old generation, then the weak reference will not be freed until the
next concurrent or full GC cycle.
Using the cache of the stock servlet as an example, let's say we know that if a particular user
accesses TPKS during her session, she is almost always likely to access it again. It makes
sense to keep the values for that stock as a strong reference in the user's HTTP session: it
will always be there for her, and as soon as she logs out, the HTTP session is cleared and the
memory reclaimed.
Now when another user comes along and needs data for TPKS , how will they find it? Since
the object is in memory somewhere, we don't want to look it up again, but the servlet code
can't search the session data for other users to find it. So in addition to keeping a strong ref-
erence to the TPKS data in the first user's HTTP session, it makes sense to keep a weak refer-
ence to that data in a global cache. Now the second user will be able to find the TPKS
data—assuming that the first user has not logged out and cleared her session. (This is the
scenario used in the heap analysis section of this chapter where the data had two references
and wasn't easily found by looking at objects with the largest retained memory.)
This is what is meant by simultaneous access. It is as if we are saying to the JVM: “Hey, as
long as someone else is interested in this object, let me know where it is, but if they no
longer need it, throw it away and I will re-create it myself.” Compare that to a soft reference,
which essentially says: “Hey, try and keep this around as long as there is enough memory
and as long as it seems that someone is occasionally accessing it.”
Search WWH ::

Custom Search