In-depth understanding of Java Collection Series II: Concurrenthashmap source Interpretation

Source: Internet
Author: User

The difference between HashMap and Hashtable

Before we formally start the topic of this article, let's compare the difference between HashMap and Hashtable:

1, Hashtable is thread-safe, it provides all the methods are used synchronized, is synchronous, and HashMap is non-thread-safe.

2. Hashtable does not allow value to be empty, otherwise it throws a null pointer exception, while key and value in HashMap can be null.

1 public synchronized v put (K key, V value) {2     //Do sure the value is not null3     if (value = = null) {4         throw New NullPointerException (); 5     }

In the map family, it is also thread-safe to compare the differences between Hashtable and Concurrenthashmap below.

The difference between Hashtable and Concurrenthashmap

1, Hashtable the way to achieve thread safety is to lock the entire hash table, that is, lock the entire table every time to let the thread exclusive. The following is the implementation of the put and get methods of Hashtable:

1 public synchronized V get (Object key) {2     Entry tab[] = table, 3     int hash = Key.hashcode (), 4     int index = (h Ash & 0x7FFFFFFF)% Tab.length; 5 for     (entry<k,v> e = Tab[index]; E! = null; e = e.next) {6         if (E.hash = = hash) && E.key.equals ( Key) {7         return e.value; 8         } 9     }10     return null;11     }
1 public synchronized v put (K key, V value) {2     //Do sure the value is not NULL 3     if (value = = null) {4
   
    throw new NullPointerException (); 5     } 6  7     //makes sure the key is not already in the Hashtable. 8     Entry tab[] = table; 9     int Hash  = Key.hashcode ();     int index = (hash & 0x7FFFFFFF)% tab.length;11 for     (entry<k,v> e = Tab[index]; E ! = NULL; E = E.next) {(         E.hash = = hash) && e.key.equals (key)) {=         e.value;14         e.value = value;1 5         return old;16         }17     }
   

2, Concurrenthashmap uses the lock separation technology, the interior is composed of segments (Segment), each segment is a small hashtable, each segment by a lock to control, so allow multiple modification operation concurrent.

3, essentially, the difference between the two is that the granularity of the lock is not the same, the granularity of the concurrenthashmap is smaller, more flexible, so that in the multi-threaded case of higher performance.

Here's the topic of this article from the CONCURRENTHASHMAP data structure:

Data structure of Concurrenthashmap

We can make a metaphor to think of Concurrenthashmap as a book, where segment as the book's volume, and the elements in the table array as headings in the chapters.

1, where segments is the entire hash table, and then there are 16 segments (Segment, where 16 is the default), each segment is a table array, each element of the array is a bucket, the bucket is stored in the hashentry.

2, Concurrenthashmap This data structure, for concurrency to make some adjustments, it divides the interval according to the concurrency level (concurrentlevel), divided into several segment, the default concurrency level is 16; For each segment capacity, The default is also 16. Of course, the concurrency level and the initial capacity of each segment can be set through the constructor function.

3. Continue to see how each segment is defined:

Static final class Segment<k,v> extends Reentrantlock implements Serializable

Segment inherits the Reentrantlock, suggesting that each segment can be used as a lock (if the Reentrantlock does not understand it, it is considered synchronized). This allows the data in each segment to be synchronized, using the lock of each segment container object itself. This approach is called a "separation lock".

4. The HASHENTRY data structure is defined as follows:

1  static Final class Hashentry<k,v> {2         final K key;3         final int hash;4         volatile V value;5         final Hashentry<k,v> Next;

When we introduced HashMap, the entry did not use final, volatile to modify the elements. The Concurrenthashmap in addition to value is not final decorated. This means that you cannot add or remove nodes from the middle or tail of the hash chain, because if you do, you must modify the reference value of next. For put operations, they can be added to the head of the hash chain, that is, the new element is placed in the header position. For the remove operation, it may be necessary to remove a node from the middle, which requires that all nodes in front of the node being deleted be copied again, and the last node points to the next node to delete the node.

In addition, to ensure that the read operation can see the most recent value, and does not adopt the Lock method, the value is set to volatile.

Positioning of data in Concurrenthashmap

Let's take a look at the code for element positioning:

Public V put (K key, V value) {        if (value = = null)            throw new NullPointerException ();        int hash = hash (Key.hashcode ());        return Segmentfor (hash). Put (key, hash, value, false);    }
Final segment<k,v> segmentfor (int hash) {        return segments[(hash >>> segmentshift) & Segmentmask] ;    }

1, first of the key hashcode code to do hash operations, mainly to reduce the hash conflict.

2, now look at the Segmentfor () method, this method is mainly to return the elements in the segments array, that is, now can be positioned to a specific segment.

3. In the Put method, the index of the 8th row is actually the subscript of the element in the table array. Then you can find the specific entry by walking through next in the one-way list.

1  V put (K key, int hash, V value, Boolean onlyifabsent) {2             lock (); 3             try {4                 int c = count;5                 if (c + + ; Threshold)//Ensure Capacity6                     rehash (); 7                 hashentry<k,v>[] tab = table;8                 int index = hash & (tab.le NGTH-1); 9                 hashentry<k,v> first = Tab[index];

4, the above 3 steps can roughly understand the process of data search, summed up is a hash operation, 2-bit operation is located in the data block. Then the chain-search efficiency is also relatively high. By now we can roughly understand why the cache is so fast.

Put method

First look at the source code of the Put method:

 1 V put (K key, int hash, V value, Boolean onlyifabsent) {2 lock (); 3 try {4 int c = Count; 5 if (c + + > Threshold)//Ensure capacity 6 rehash (); 7 hashentry<k,v>[] tab = table; 8 int index = hash & (tab.length-1);                 9 hashentry<k,v> first = tab[index];10 hashentry<k,v> e = first;11                 while (E! = null && (E.hash! = Hash | |!key.equals (E.KEY))) E = e.next;13 14 V oldvalue;15 if (E! = null) {OldValue = E.value;17 if (!                     onlyifabsent) E.value = value;19}20 else {21 OldValue = null;22 ++modcount;23 Tab[index] = new hashentry<k,v> (key, hash , first, value), Count = C;Write-volatile25}26 return oldvalue;27} finally {Unloc K (); 29}30}

1, from the 2nd line can be seen, the method is held in the case of a lock is executed. This is of course for concurrency security, after all, modifying the data is not possible for concurrent operations.

2, in the 4–6 line, count represents the capacity of the segment, first add 1 operations, and then determine whether the expansion is required. Expansion is also expanded by one-fold on the basis of the original capacity.

3, we start from the 10th line to interpret: E takes the position of the list of the head element.

4, the 11th line is to locate the entry in the linked list, if not found, continue to traverse the unidirectional linked list through next.

5, 第15-19 Line, is the operation of the substitution, that is, the position of the original E is not empty, then the original value as the return value of the Put method, and the value values are replaced with the latest (Onlyifabsent==false)

6, 第20-25 Line, is the operation of the new element, that is, the position through the key to the location and there is no element, then create a new entry placed in that position. and modify the count value to be up to date.

Get method

First look at the source code of the Get method:

1  V get (Object key, int hash) {2             if (count! = 0) {//Read-volatile 3                 hashentry<k,v> e = GetFirst (hash) ; 4                 while (E! = null) {5                     if (E.hash = = Hash && key.equals (E.key)) {6                         v v = e.value; 7                         if (V! = nul L) 8                             return v; 9                         return Readvalueunderlock (e);//Recheck10                     }11                     e = e.next;12                 }13             }14             Return null;15         }

1, by contrast, you can know that a get operation does not require a lock.

2, the first step is to access the count variable, which is a volatile variable, because all modifications in the structural modification of the last step to write the count variable, through this mechanism to ensure that the get operation can get the latest structure updates.

3, the following is the traversal of the list, according to the hash value, key value to query entry, if found to return. Otherwise, it can be read again if there is a lock. Wait a while, what's the situation?

4, we come to seriously analyze why the query value is empty when the value is also in the case of a lock to read again. This is somewhat confusing, theoretically the value of the node is impossible to empty, because in the put operation is judged, if NULL throws a null pointer exception.

V Get (Object key, int hash) {         if (count! = 0) {//1             hashentry<k,v> e = GetFirst (hash);             while (E! = null) {                 if (E.hash = = Hash && key.equals (E.key)) {                     v v = e.value;                     if (v = null)//2                         return v;                     Return Readvalueunderlock (e); Recheck                 }                 e = E.next;             }         }         return null;     }

In the above code there are two lines of code, I marked with a red font.

Between get code 1 and 2, another thread added a entry

1, the person is crazy is: just this thread new entry is we want to get. Let's take a look at the put method to add a entry process:

2, the new entry is definitely placed in the head node position, which has been explained in the previous analysis.

3. Newentry objects are created by means of new hashentry<k,v> (key, hash, first, value). If a thread is just new to this object, the current thread is get it. Because there is no synchronization, the Newentry object that the current thread obtains is an object reference that is not fully constructed. Value at this time may be empty . So there is a front lock again get once again action.

4, in addition to discuss the problem of DCL, similar to this, in the absence of lock synchronization, the new object for multi-threaded to see the state of this object is not guaranteed, here is also possible when a thread new this object is not finished executing the constructor is another thread to get this object reference.

Between get code 1 and 2, another thread modifies the value of a entry

Value is modified with a volatile value, which guarantees that the modified values are obtained when reading.

Between get code 1 and 2, another thread deleted a entry

Suppose our list element is: E1, E2, E3, E4. The entry that is deleted by another thread is E3. Since next in the hashentry cannot be changed, we cannot directly point the E2 next directly to E4, but we need to copy the node before the Delete node to form a new linked list.

Approximate implementation:

If we get the same happens to be E3, maybe we just follow the list E1, this is another thread to delete the E3, and the current thread will continue along the old list to find E3, there is no way to guarantee the real-time.

The count variable is judged in code 1, which guarantees that the 1-bit can see the other thread modified. Between 1 and 2, another thread has deleted the entry node, and there is no way to ensure that the latest is seen.

But it doesn't matter, even if we return to E3, he was deleted by other threads, and the exposed E3 will not affect our new list.

This is actually an optimistic design, because the "delete" and "change" of other threads will not affect our data, so only the "new" operation has done a security check, which is the non-null check of location 2.

Remove method

Go directly to the source code

 1 V Remove (object key, int hash, object value) {2 lock (); 3 try {4 int c = Coun t-1; 5 hashentry<k,v>[] tab = table; 6 int index = hash & (tab.length-1); 7 hashentry<k,v> first = Tab[index]; 8 hashentry<k,v> e = first; 9 while (E! = null && (E.hash! = Hash | |!key.equals (E.KEY))) E = e.next;11                     OldValue = null;13 if (E! = null) {+ V = e.value;15  if (value = = NULL | | value.equals (v)) {OldValue = v;17//All                         Entries following removed node can stay18//in list, but all preceding ones need to be19 cloned.20 ++modcount;21 hashentry<k,v> Newfirst = E.next;22 for (hashentry<k,v> p = first; P! = e; p = p.next) Newfirst = new hashentry<k,v> (p.) Key, p.hash,24 Newfirst, P.value); [index] = newfirst;26 count = C; Write-volatile27}28}29 return oldvalue;30} finally { Unlock (); 32}33}

1, the entire positioning process and the put operation is similar, first locate to the segment, and then delegate to the section of the remove operation. When multiple delete operations are concurrent, they can be performed concurrently, as long as they are in a different segment.

2, the previous process is similar, we start directly from the 21st line analysis. First, take the head node at that location. A For loop is then performed to re-copy the entry before the element to be deleted. This is controlled by the next invariance in entry. Let's look at the following:

After deleting element 3:

3, the remove operation has two places to note, one is the deletion node exists, the last step to delete the value of the count minus 1. The other is that when remove executes, the table is assigned a local variable tab, because table is a volatile variable, and the cost of reading and writing volatile variables is significant. The compiler does not have any optimizations for reading and writing volatile variables, and accessing non-volatile instance variables directly multiple times does not have much effect, and the compiler responds optimally.

In-depth understanding of Java Collection Series II: Concurrenthashmap source Interpretation

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.