Java: Use ConcurrentHashmap for Custom Caching
By admin on Feb 15, 2009 in Java, open source
Here is a good article to tell the different between different Map implementation.
Java theory and practice: Concurrent collections classes
Quoted
The
ConcurrentHashMap
class fromutil.concurrent
(which will also appear in thejava.util.concurrent
package in JDK 1.5) is a thread-safe implementation ofMap
that offers far better concurrency thansynchronizedMap
. Multiple reads can almost always execute concurrently, simultaneous reads and writes can usually execute concurrently, and multiple simultaneous writes can often execute concurrently. (The relatedConcurrentReaderHashMap
class offers similar multiple-reader concurrency, but allows only a single active writer.)ConcurrentHashMap
is designed to optimize retrieval operations; in fact, successfulget()
operations usually succeed with no locking at all. Achieving thread-safety without locking is tricky and requires a deep understanding of the details of the Java Memory Model. TheConcurrentHashMap
implementation, along with the rest ofutil.concurrent
, has been extensively peer-reviewed by concurrency experts for correctness and thread safety. We will look at the implementation details ofConcurrentHashMap
in next month’s article.
ConcurrentHashMap
achieves higher concurrency by slightly relaxing the promises it makes to callers. A retrieval operation will return the value inserted by the most recent completed insert operation, and may also return a value added by an insertion operation that is concurrently in progress (but in no case will it return a nonsense result).Iterators
returned byConcurrentHashMap.iterator()
will return each element once at most and will not ever throwConcurrentModificationException
, but may or may not reflect insertions or removals that occurred since the iterator was constructed. No table-wide locking is needed (or even possible) to provide thread-safety when iterating the collection.ConcurrentHashMap
may be used as a replacement forsynchronizedMap
orHashtable
in any application that does not rely on the ability to lock the entire table to prevent updates.These compromises enable
ConcurrentHashMap
to provide far superior scalability overHashtable
, without compromising its effectiveness in a wide variety of common-use cases, such as shared caches.
Also, if possible when you have a multithread program, and when you need to reload cache, it is good to construct a new cache, and then swap the instance. E.g.
AppConfigFactory tempInstance = instance;
newInstance = new AppConfigFactory(configFile);
instance = newInstance;
Popularity: 2% [?]
Post a Comment