Java Reference
In-Depth Information
The reason to cache that data is that requests tend to come in for certain items more often
than for others. If TPKS is the most requested stock, it can be expected to remain in the soft
reference cache. On the other hand, a lone request for KENG will live in the cache for a while
but eventually be reclaimed. This also accounts for requests over time: a cluster of requests
for DNLD can reuse the result from the first request. As users realize that DNLD is a bad invest-
ment, those cached items will eventually age out of the heap.
When, exactly, is a soft reference freed? First the referent must not be strongly referenced
elsewhere. If the soft reference is the only remaining reference to its referent, the referent is
freed during the next GC cycle only if the soft reference has not recently been accessed. Spe-
cifically, the equation functions like this pseudocode:
long ms = SoftRefLRUPolicyMSPerMB * AmountOfFreeMemoryInMB;
if (now - last_access_to_reference > ms)
free the reference
There are two key values here. The first is set by the -XX:SoftRefLRUPolicyMSPerMB= N
flag, which has a default value of 1,000.
The second value is the amount of free memory in the heap (once the GC cycle has com-
pleted). Since the heap is sized dynamically, the JVM has two choices when it calculates how
much memory in the heap is free: the free memory in the heap at its current size, or the free
memory in the heap if it were to expand to its maximum capacity. The choice of those values
is determined by the compiler in use. The client compiler bases that value on the available
memory in the current heap, while the server compiler uses the maximum possible size of the
heap.
So how does that all work? Take the example of a JVM using the server compiler and a 4 GB
heap. After a full GC (or a concurrent cycle), the heap might be 50% occupied; the free heap
is therefore 2 GB. The default value of SoftRefLRUPolicyMSPerMB (1,000) means that any
soft reference that has not been used for the past 2,048 seconds (2,048,000 ms) will be
cleared: the free heap is 2,048 (in megabytes), which is multiplied by 1,000:
long ms = 2048000; // 1000 * 2048
if (System.currentTimeMillis() - last_access_to_reference_in_ms > ms)
free the reference
If the 4 GB heap is 75% occupied, objects not accessed in the last 1,024 seconds are re-
claimed, and so on.
Search WWH ::




Custom Search