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
ConcurrentHashMapclass fromutil.concurrent(which will also appear in thejava.util.concurrentpackage in JDK 1.5) is a thread-safe implementation ofMapthat 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 relatedConcurrentReaderHashMapclass offers similar multiple-reader concurrency, but allows only a single active writer.)ConcurrentHashMapis 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. TheConcurrentHashMapimplementation, 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 ofConcurrentHashMapin next month’s article.
ConcurrentHashMapachieves 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).Iteratorsreturned 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.ConcurrentHashMapmay be used as a replacement forsynchronizedMaporHashtablein any application that does not rely on the ability to lock the entire table to prevent updates.These compromises enable
ConcurrentHashMapto 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% [?]
