Re: Implementing caches that may be cleared if heap space shrinks
away
Matt Humphrey wrote:
"Tassilo Horn" <tassilo@member.fsf.org> wrote in message
news:87k56cftj9.fsf@thinkpad.tsdh.de...
if (words.get() == null) {
initializeCache();
} else if (words.get().containsKey(word)) {
return words.get().get(word);
}
And there may be the possibility that after the check the soft ref is
cleared before I access it...
I don't think this is true. From the javadocs on SoftReference---
"As long as the referent of a soft reference is strongly reachable, that is,
is actually in use, the soft reference will not be cleared."
At the time you retrieve the soft reference it is either null (already
cleared) or it refers to the object. If it refers to the object it is now
strongly reachable via the local variable and will not be cleared.
But there is no local variable in the code above. Having tested
words.get() and found it to be not null, there's no hard reference, so
there's a slim chance of it becoming null before the next 'if'. I think
the first thing you need to do with any Reference is to get() it into a
local variable, and use that from there:
HashMap<String, WordInfo> cache = words.get();
if (cache == null) {
initializeCache();
} else if (cache.containsKey(word)) {
return cache.get(word);
}
--
ss at comp dot lancs dot ac dot uk