I have a cache which I implemented using a simeple HashMap. like -
HashMap cache = new HashMap();
It is not safe without a proper memory barrier.
One would think that the assignment of cache (cache = newCache) would happen after the steps to populate the cache. However, other threads may suffer from reordering of these statements so that the assignment may appear to happen before populating the cache. Thus, it is possible to grab the new cache before it's fully constructed or even worse see a ConcurrentModificationException.
You need to enforce the happens-before relationship to prevent this reordering, and declaring the cache as volatile would achieve that.
What about CopyOnWrite.. collections:
java.util.concurrent.CopyOnWriteArraySet
java.util.concurrent.CopyOnWriteArraySet
and org.apache.mina.util.CopyOnWriteMap
They can be a good match in your case and they are thread-safe.
Seems to be OK. Be sure refreshCache
is not called too frequently or mark as synchronized
.
You should mark the cache as volatile
.
While you note that other threads may continue using a stale cache for "a long time" you should note that, without a synchronization edge, they are likely to continue using the stale cache forever. That's probably not the desired behavior.
In order of preference (mostly due to readability):
AtomicReference<Map<>>
volatile
See also this question.