[Reprint] How java. util. Concurrent. concurrenthashmap can provide higher concurrency without compromising thread security

Source: Internet
Author: User

[Reprint] How java. util. Concurrent. concurrenthashmap can provide higher concurrency without compromising thread security

 

Concurrenthashmap is part of Doug Lea's util. Concurrent package, which provides a higher degree of concurrency than hashtable or synchronizedmap. Moreover, for most successful get () operations, it will try to avoid full locking. The result is that the concurrent application has a very good throughput. This month, Brian Goetz carefully analyzed the concurrenthashmap code and discussed how Doug Lea achieved this remarkable result without compromising thread security. Share your thoughts on this article with the author and other readers on the Forum (you can also click the discussion at the top or bottom of the article to visit the Forum ).
In the phase of Java's Theory and Practice ("concurrent collections classes") in July, we briefly reviewed the bottleneck of scalability, we also discussed how to use the shared data structure method to obtain higher concurrency and throughput. Sometimes the best way to learn is to analyze the results of experts, so this month we will analyze the concurrenthashmap implementation in Doug Lea's util. Concurrent package. JSR 133 specifies a version of concurrenthashmap, Which is optimized for the Java Memory Model (jmm) and will be included in the Java. util. Concurrent package of JDK 1.5. Versions in util. Concurrent have passed the thread security audit in both the old and new memory models.

Optimize throughput
Concurrenthashmap uses several techniques to get high concurrency and avoid locking, including for different hash buckets (buckets) use multiple write locks and the uncertainty of using jmm to minimize the lock holding time-or avoid getting the lock at all. For most general usage, It is optimized. These operations often retrieve a value that may already exist in the map. In fact, most successful get () operations can run without any locks. (Warning: do not try this on your own! It's not as easy as it looks to be smarter than jmm. The util. Concurrent class is compiled by concurrent experts and has undergone rigorous peer reviews on jmm security. )

Multiple write locks
We can recall that hashtable (or alternative solution collections. the main obstacle to synchronizedmap's scalability is that it uses a map-wide lock. To ensure the integrity of insert, delete, or search operations, such a lock must be maintained, and sometimes it is even necessary to maintain such a lock to ensure the integrity of iterative traversal operations. In this way, as long as the lock is kept, other threads are basically prevented from accessing the map, even if the processor is idle, it cannot be accessed, which greatly limits the concurrency.

Concurrenthashmap abandons the Lock of a single map range and is replaced by a collection composed of 32 locks. Each lock is responsible for protecting a subset of the hash bucket. The lock is mainly used by variable operations (put () and remove. Having 32 independent locks means a maximum of 32 threads can modify the map at the same time. This does not necessarily mean that when the number of threads for write operations on the map is less than 32 concurrently, other write operations will not be blocked -- 32 is a theoretical concurrency limit for the write thread, however, this value cannot be reached. However, 32 is still much better than 1, and it is sufficient for most applications running on the current generation of computer systems.

Map operations
There are 32 independent locks, each of which protects a subset of the hash bucket. In this way, all 32 locks must be obtained for the operation that exclusively accesses map. Some map-range operations, such as size () and isempty (), may be able to lock the entire map (by appropriately limiting the semantics of these operations), but some operations, for example, map shuffling (expanding the number of hash buckets and re-distributing elements as map grows) requires exclusive access. The Java language does not provide an easy way to obtain a set of locks of variable sizes. It is rare to do this. Once this happens, we can use recursive methods.

Jmm Overview
Before entering the implementation of put (), get (), and remove (), let's take a brief look at jmm. Jmm is in charge of the way in which a thread's actions on the memory (read and write) affect the actions of other threads on the memory. Because processor registers and pre-processing cache are used to improve the performance of memory access, the Java language specification (JLS) allows some memory operations not to be immediately visible to all other threads. Two language mechanisms are available to ensure the consistency of cross-thread memory operations-synchronized and volatile.

According to JLS, "in the absence of explicit synchronization, an implementation can freely update the primary storage. The order in which the primary storage is updated may be unexpected ." It means that if there is no synchronization, write operations in a certain sequence in a given thread may display different sequence for another different thread, the time for updating memory variables to be transmitted from one thread to another is unpredictable.

Although the most common reason for using synchronization is to ensure atomic access to key parts of the Code, synchronization actually provides three independent functions-atomicity, visibility, and sequence. Atomicity is very simple-synchronous implementation of a reentrant mutex prevents more than one thread from simultaneously executing code blocks protected by a given monitor. Unfortunately, most articles only focus on Atomicity and ignore other aspects. However, synchronization also plays a very important role in jmm, which causes the JVM to execute memory barriers (memory barrier) when obtaining and releasing monitors ).

After a thread obtains a monitor, it executes a read barrier to invalidate all the variables cached in the local memory of the thread (such as the processor cache or Processor register, this will cause the processor to re-read the variables used by the synchronization code block from the main memory. Similarly, when the monitor is released, the thread executes a write barrier to write all the modified variables back to the primary storage. The combination of mutex exclusive and memory barrier means that as long as you follow the correct synchronization rules during program design (that is, every time you write a variable that may be accessed by other threads, or use synchronization when reading a variable that may be modified by another thread), each thread will get the correct value of the shared variable it uses.

If the shared variables are not synchronized during access, some strange things will happen. Some changes may be immediately reflected by the thread, while others may take some time (this is due to the nature of the associated cache ). As a result, you cannot ensure that the memory content is consistent without synchronization (the related variables may be inconsistent with each other ), or you cannot get the current memory content (some values may be outdated ). The common method to avoid such dangerous situations (also recommended) is of course to use synchronization correctly. However, in some cases, for example, some library classes that are widely used, such as concurrenthashmap, in the development process, some additional professional skills and efforts are required (which may be many times more than general development) to achieve high performance.

Concurrenthashmap implementation
As mentioned above, the data structure used by concurrenthashmap is similar to the implementation of hashtable or hashmap. It is a variable array of the hash bucket, and each concurrenthashmap is composed of a map. entry element chain structure, as shown in Listing 1. Unlike hashtable and hashmap, concurrenthashmap uses a fixed lock pool instead of a collection lock, which forms a partition of the bucket set.

Listing 1. Map. Entry element used by concurrenthashmap

Protected static class entry implements map. Entry {
Protected final object key;
Protected volatile object value;
Protected final int hash;
Protected final entry next;
...
}

No need to lock the traversal Data Structure
Unlike hashtable or a typical lock pool map implementation, the concurrenthashmap. Get () operation does not necessarily need to obtain the locks associated with the relevant bucket. If no lock is used, the implementation must be able to process outdated or inconsistent values of all the variables it uses, such as the list header pointer and map. the field of the entry element (including the link pointer that forms the linked list of each hash bucket entry ).

Most concurrent classes use synchronization to ensure exclusive access to a data structure (and maintain data structure consistency ). Concurrenthashmap does not adopt exclusivity and consistency. Its linked list is carefully designed, so its implementation can detect whether its list is consistent or outdated. If it detects that its list is inconsistent or out of date, or simply cannot find the entries it is looking for, it will synchronize the appropriate bucket lock and search the entire chain again. In general, you can optimize the search. The so-called general condition is that most search operations are successful and the number of searches is more than the number of inserts and deletes.

Immutability
An important source of inconsistency can be avoided. The method is to make the entry element close to immutability-all fields except value fields (which are variable) are final. This means that you cannot add elements to or end of a hash chain, or delete elements from or to the end of a hash chain. Instead, you can only add elements from the beginning of a hash chain, the delete operation includes cloning a part of the entire chain or chain and updating the header pointer of the list. So as long as there is a reference to a hash chain, even if you may not know whether there is any reference to the List header node, you can also know that the structure of the rest of the list will not change. In addition, because the value field is variable, you can immediately see the update of the value field, which greatly simplifies the compilation of MAP implementation that can process potential out-of-date memory.

The new jmm provides initialization security for final variables, but the old jmm does not. This means that another thread may see the default value of the final field, rather than the value provided by the object's constructor. This must be detected at the same time by ensuring that the default value of each field in the entry is not a valid value. After the list is constructed, if any entry field has its default value (zero or empty), the search will fail, prompting you to synchronize get () and repeat the link.

Search operations
The search operation first refers to the search header pointer of the target bucket (which is completed without being locked, so it may be outdated ), then, you can traverse the bucket chain without obtaining the bucket lock. If it cannot find the value to be searched, It synchronizes and tries to find the entry again, as shown in Listing 2:

Listing 2. concurrenthashmap. Get () Implementation

Public object get (Object key ){
Int hash = hash (key); // throws NULL pointer exception if key is null

// Try first without locking...
Entry [] tab = table;
Int Index = hash & (Tab. Length-1 );
Entry first = tab [Index];
Entry E;

For (E = first; e! = NULL; E = E. Next ){
If (E. Hash = hash & eq (Key, E. Key )){
Object value = E. value;
// Null values means that the element has been removed
If (value! = NULL)
Return value;
Else
Break;
}
}

// Recheck under synch if key apparently not there or interference
Segment seg = segments [hash & segment_mask];
Synchronized (SEG ){
Tab = table;
Index = hash & (Tab. Length-1 );
Entry newfirst = tab [Index];
If (E! = NULL | first! = Newfirst ){
For (E = newfirst; e! = NULL; E = E. Next ){
If (E. Hash = hash & eq (Key, E. Key ))
Return e. value;
}
}
Return NULL;
}
}

Delete operation
Because a thread may see the outdated value of The Link pointer in the hash chain, simply deleting an element from the chain is not enough to ensure that other threads will not continue to see the deleted value while searching. On the contrary, we can see from listing 3 that the delete operation is divided into two processes: First, find the appropriate entry object and set its value field to null, then, clone the elements in the chain from the beginning to the elements to be deleted, and connect them to the parts after the elements to be deleted. Because the value field is variable, if another thread is searching for the deleted element in an outdated chain, it will immediately see a null value and know to use synchronization to re-search. Eventually, the deleted elements in the original hash chain will be collected as garbage.

Listing 3. concurrenthashmap. Remove () Implementation

Protected object remove (Object key, object Value ){
/*
Find the entry, then
1. Set Value Field to null, to force get () to retry
2. Rebuild the list without this entry.
All entries following removed node can stay in list,
All preceding ones need to be cloned. traversals rely
On this strategy to ensure that elements will not be
Repeated during iteration.
*/

Int hash = hash (key );
Segment seg = segments [hash & segment_mask];

Synchronized (SEG ){
Entry [] tab = table;
Int Index = hash & (Tab. Length-1 );
Entry first = tab [Index];
Entry E = first;

For (;{
If (E = NULL)
Return NULL;
If (E. Hash = hash & eq (Key, E. Key ))
Break;
E = E. Next;
}

Object oldvalue = E. value;
If (value! = NULL &&! Value. Equals (oldvalue ))
Return NULL;

E. value = NULL;

Entry head = E. Next;
For (entry P = first; P! = E; P = P. Next)
Head = new entry (P. Hash, P. Key, P. Value, head );
Tab [Index] = head;
Seg. Count --;
Return oldvalue;
}
}

Figure 1 shows the hash chain before an element is deleted:

Figure 1. Hash Chain

Figure 2 shows the chain after element 3 is deleted:

Figure 2. delete an element

Insert and update operations
Put () implementation is very simple. Like remove (), put () will keep the bucket lock during execution, but since not all put () needs to get the lock, therefore, this does not necessarily block the execution of other read threads (nor block other write threads from accessing other buckets ). It first searches for the required key values in the appropriate hash chain. If it can be found, the value field (Changeable) is directly updated. If not found, a new entry object is created to describe the new map, and then inserted to the header of the bucket list.

Weak Consistent iterator
The semantics of the iterator returned by concurrenthashmap is different from that returned by Ava. the iterator In the util set; and it is weakly consistent instead of fail-fast (the so-called fail-fast means that when an iterator is being used, an exception is thrown when the underlying set is modified ). When a user calls keyset (). iterator () to retrieve a group of hash keys from the iterator, the implementation simply uses synchronization to ensure that the header pointer of each chain is the current value. The next () and hasnext () operations are defined in an obvious way, that is, traversing each chain and then going to the next chain until all the chains are traversed. The Weak Consistent iterator may or may not reflect the insert operation in the iterator iteration process, but it will certainly reflect the update or delete operation of the key that the iterator has not reached, and returns a maximum of once for any value. The iterator returned by concurrenthashmap does not throw a concurrentmodificationexception.

Dynamic resizing
As the meta-prime number in map increases, the hash chain will become longer, so the retrieval time will also increase. In a sense, it is very important to increase the number of buckets and rearrange the values. In some classes such as hashtable, this is simple because it is possible to keep an exclusive lock applied to the entire map. In concurrenthashmap, if the length of a chain exceeds a threshold value during each entry insertion, the chain is marked as needing to be adjusted. When there are enough chains marked as needing to be adjusted, concurrenthashmap uses Recursion to get the locks on each bucket and rearrange the elements in each bucket to a new and larger hash table. In most cases, this happens automatically and is transparent to callers.

Don't lock?
It seems that the get () operation can be successfully completed without locking, because the Value Field of the entry is variable, which is used to detect updates and deletions. At the machine level, the easily changed and synchronized content will usually be translated into the same cache consistent primitive at the end, so there will be some locks here, although only fine-grained and not scheduled, or the JVM overhead of the monitor is not obtained or released. However, in addition to semantics, in many general cases, the number of searches exceeds the number of inserts and deletions, so the concurrency obtained by concurrenthashmap is quite high.

Conclusion
Concurrenthashmap is a very useful class for many concurrent applications, and it is a good example to understand how jmm achieves high performance. Concurrenthashmap is a typical encoding. It can be written only when you have a deep understanding of concurrency and jmm. Use it, learn from it, and enjoy it-unless you are an expert in Java concurrency, you should not try it yourself.

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.