Concurrenthashmap combines the advantages of both Hashtable and HashMap.
Hashtable is doing thread synchronization, HashMap does not consider synchronization. So HashMap is more efficient in single-threaded process, Hashtable can guarantee the correctness of the program under the multi-thread synchronization operation. However,the entire structure must be locked by the H ashtable each time the synchronization operation is performed.
The appearance of Concurrenthashmap is to solve the problem of Hashtable synchronization lock whole data structure. The way to Concurrenthashmap locks is fine grain size.
Concurrenthashmap divides the hash table into 16 buckets (the default), such as a get/put/remove operation that requires only a single bucket to be locked.
Concurrenthashmap locks the entire hash table only when the size is in operation.
The following is an example of a concurrenthashmap local cache that is implemented by itself:Concurrenthashmap and guava caches need to display their own delete cache
ImportJava.util.concurrent.ConcurrentHashMap; Public classConcurrenthashmaptest {Private Staticconcurrenthashmap<string, string> cachemap =NewConcurrenthashmap<>(); /*** Get Cached objects * *@paramAccount *@return */ Public Staticstring GetCache (String account) { account=Getcachekey (account); //if the account is in the buffer, the value is returned if(Cachemap.containskey (account)) {returnCachemap.get (account); } //If the account is not in the cache, cache the account object in ConcurrenthashmapInitcache (account); returnCachemap.get (account); } /*** Initialize Cache * *@param Account*/ Private Static voidInitcache (String account) {//database queries are typically performed to cache the results of a queryCachemap.put (account, "18013093863"); } /*** Splicing a cache key * *@paramAccount *@return */ Private Staticstring Getcachekey (String account) {returnThread.CurrentThread (). GetId () + "-" +Account ; } /*** Removing cache information * *@param Account*/ Public Static voidRemoveCache (String account) {cachemap.remove (Getcachekey); }}
Java Learning Concurrenthashmap Implementation of a local cache