Java Concurrenthashmap Source Depth analysis

Source: Internet
Author: User

Welcome reprint, please attach the source:
http://blog.csdn.net/as02446418/article/details/47004573

Let's first look at the declaration of the Concurrenthashmap class:

    publicclass ConcurrentHashMap<K, V> extends AbstractMap<K, V>        implements ConcurrentMap<K, V>, Serializable

Among them, this class inherited the JAVA.UTIL.ABSTRACTMAP in the existing implementation, this in the previous collation HashMap has been mentioned, focus on the implementation of the following interface Concurrentmap and serializable. Serializable is serialized, and the definition of Concurrentmap is as follows:

publicinterface ConcurrentMap<K, V> extends Map<K, V> {    V putIfAbsent(K key, V value);    boolean remove(Object key, Object value);    boolean replace(K key, V oldValue, V newValue);    V replace(K key, V value);}

4 methods are specified.

    • V Putifabsent (K key, v value); If you do not have this key, then put this key-value, return null, otherwise return the key corresponding to the value.

    • Boolean remove (Object key, object value); Remove key and corresponding value if key does not correspond to value, remove failed

    • Boolean replace (K key, v OldValue, v newvalue); Replaces the key corresponding to the value, only if the current value is the old value

    • V Replace (K key, v value); Replace the value corresponding to the key, as long as there is currently a value

These methods are implemented in Concurrenthashmap, which are mentioned later in this section.

1. Construction method and segment realization of Concurrenthashmap
First look at the construction method:

publicConcurrentHashMap(int initialCapacity,                             floatint concurrencyLevel)

There are several overloaded methods, saying that this parameter is the most complete, there are 3 parameters, in addition to the hashmap involved in the Loadfactor and initialcapacity, there is a concurrencylevel, translation is the level of concurrency or concurrency.

In this case, there is a segments array object in Concurrenthashmap, the element type is Concurrenthashmap's inner class segment, and Concurrencylevel is the size of the segments array.

Let's take a look at this segment class:

staticfinalclass Segment<K,V> extends ReentrantLock implements Serializable

The segment extends the Reentrantlock and implements the serializable interface. In addition, we find that the things implemented in this class are very similar to JAVA.UTIL.HASHMAP.

In fact, this class is the key to the entire CONCURRENTHASHMAP implementation. I think, as the reader of this article, you should use a variety of databases, take the MySQL InnoDB engine, it is in addition to support table-level lock unexpectedly, but also support row-level lock, the significance is that this reduces the lock granularity, when only a row of data to operate, It is likely that there is no need to restrict data from other rows in the same table. In this class, the segment also plays the same role. Each segment itself is a reentrantlock, only the data to be modified exists in the same segment, it is possible to lock up, which improves the efficiency of multi-threaded situations, there is no need for all threads to wait for the lock.

2. Get () method source code Analysis
Let's look at the implementation of the Get () method first.

 PublicVGet(Object key) {segment<k,v> s;//Manually integrate access methods to reduce overheadhashentry<k,v>[] tab;intH = hash (key);LongU = (((H >>> segmentshift) & Segmentmask) << sshift) + sbase;if((s = (segment<k,v>) unsafe.getobjectvolatile (segments, u))! =NULL&& (tab = s.table)! =NULL) { for(hashentry<k,v> e = (hashentry<k,v>) unsafe.getobjectvolatile (tab, (Long) ((Tab.length-1) & H)) << Tshift) + tbase); E! =NULL; E = E.next) {k k;if(k = e.key) = = Key | | (E.hash = = h && key.equals (k)))returnE.value; }    }return NULL;}

In fact, it is the hash value computed by key, the corresponding segment object is determined, and the corresponding object of the hash value in table and table is obtained by atomic manipulation.

We can see that in this process, there is no explicit use of locks, only through the unsafe class and atomic operations, to avoid blocking, improve performance.

3. Put () and putifabsent () method Analysis
First look at the source of the Put () method:

 PublicVput(K key, Vvalue) {segment<k,v> s;if(value==NULL)Throw NewNullPointerException ();inthash = hash (key);intj = (hash >>> segmentshift) & Segmentmask;if((s = (segment<k,v>) unsafe.getobject//nonvolatile; recheck(Segments, (J << Sshift) + sbase)) ==NULL)//In Ensuresegments = ensuresegment (j);returnS.put (key, hash,value,false);}

We see that the final is the call of the put () method using segment, and the Putifabsent () method is called only for the last parameter.

Let's take a closer look at the invocation of the segment put () method:

FinalV put (K key,intHash, V value,Booleanonlyifabsent) {hashentry<k,v> node = Trylock ()?NULL: Scanandlockforput (key, hash, value); V OldValue;Try{hashentry<k,v>[] tab = table;int Index= (Tab.length-1) & Hash; hashentry<k,v> first = entryat (tab,Index); for(hashentry<k,v> e = first;;) {if(E! =NULL) {k k;if(k = e.key) = = Key | | (E.hash = = Hash && key.equals (k))) {oldValue = E.value;if(!onlyifabsent)                        {e.value = value;                    ++modcount; } Break;            } e = E.next; }Else{if(Node! =NULL) Node.setnext (first);Elsenode =NewHashentry<k,v> (hash, key, value, first);intc =Count+1;if(C > Threshold && tab.length < maximum_capacity) rehash (node);ElseSetentryat (tab,Index, node); ++modcount;Count= C; OldValue =NULL; Break; }        }    }finally{unlock (); }returnOldValue;}

Compared to JAVA.UTIL.HASHMAP, there are two different places, basically similar. One is the judgment processing of the onlyifabsent parameter. The other is to lock the whole operation process and do a bit of clever processing in the lock place. is in the process of waiting for the lock, constantly searching and constructing node node object, whether or not this method eventually created to the node nodes, when this method returns, must have obtained this segment corresponding lock.

and the search and creation of the node in the loop, on the one hand is to do the traversal of the node query, on the other hand, also played the role of spin lock, to avoid the direct call lock () and other lock blocking, because this will be in the system implementation level blocking and wake-up threads, there is a certain switching costs, to improve efficiency.

4. Overview
In fact, throughout the implementation of the class, it will certainly involve the processing of segment and the invocation of the method. The invocation of these methods, divided into read operations and write processing, usually the read operation is not used to lock, and in the modification operation, such as remove () replace () and so on are similar to put (), during the entire operation of the segment to try to lock and spin the premise of the lock, and finally release the lock. These write operations are essentially equivalent to the Scanandlockforput () method in put (), except that nodes need to be created.

On the whole, because segment reduces the lock granularity in concurrency and locks are used in write operations. It guarantees the thread safety of the whole concurrenthashmap and also guarantees the efficiency of the Concurrency Runtime.

5. Other
There is no treemap in the Java.util.conccurent package, but for ordered containers, there is a map implementation concurrentskiplistmap based on the skip list data structure, and there are skip The list's concurrentskiplistset, like the set in the Java.util package, is map-based.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Concurrenthashmap Source Depth analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.