The Java Collection (25) Concurrenthashmap

Source: Internet
Author: User

Reprint please indicate source: http://www.cnblogs.com/lighten/p/7520808.html

1. Preface

This chapter describes one of the most frequent concurrent collection classes used by Concurrenthashmap, which described HashMap and Hashtable earlier, pointing out the problem with Hashtable. Although you can use the Collections.synchronizedmap method to wrap HashMap to complete a thread-safe map, this is far from satisfying our performance needs. Because map is used very often, key-value pairs are very common in programs, and every time a put or get operation locks the entire map, it is definitely bad. It is worth mentioning that Concurrenthashmap in the early version seems to have taken a segmented lock method to control, but at least after JDK7 (only loaded 7,8) and did not take this way, but using CAS operation and synchronized lock faster method of implementation, Segment the existence of the meaning is only to be compatible with the previous version, but the actual is a kind of segmented lock idea, the lock is a hash bucket.

Typically, retrieval operations (including get) are non-blocking, so they may overlap with update operations (PUT,REMOVE). The results of the search are affected by the most recent update operation, which simply means that the update operation for a key is a happens-before relationship for any retrieval operation, so the key shows the most recently updated value. For the total operation (putall,clear). Retrieves an insertion or removal effect that may be affected by a partial key-value pair. Similarly, iterators are affected by the state of the hash table at some point in time of creation and do not throw concurrency exceptions, but the design of iterators only takes into account the use of single threads.

When the conflict is serious, the hash table automatically expands, and the expansion traversal is considered to be a slow operation, and if it is possible to set the size by the initial capacity construction parameters, Loadfactor and HashMap will default to 0.75.

Note Concurrenthashmap is not allowed to be a key or a value of null,hashmap.

2.concurrenthashmap2.1 Data structure

Concurrenthashmap has a number of parameters and is a partial variable parameter. There are also a number of constant parameters:

Maximum_capacity: Maximum capacity 230.

Default_capacity: Default Capacity 16

Max_array_size: Maximum array size (toarray, etc.) integer.max_value-8

Default_concurrency_level: Default concurrency Level 16 (useless, pre-compatible version)

Load_factor: Load Factor 0.75

Treeify_threshold: Change the threshold of red and black trees by 8

Untreeify_threshold: Normal linked list threshold value 6

Min_treeify_capacity: The smallest table capacity can be converted to red-black trees only if it exceeds this capacity list. At least 4 times times the Treeify_threshold, default 64

Min_transfer_stride: The minimum number of rebuild buckets per transfer step

Other parameters:

Table: basic hash table, size is 2n

Use when nexttable:resize.

Basecount: Basic statistical value, usually used when there is no competition

SIZECTL: Table initialization and control of resize

Transferindex:resize the index of a table split +1

Cellsbusy:resize or create a countercells spin lock

Countercells:counter cells table, non-empty time size is 2n

2.2 Basic operations

Gets an element that has no lock:

The steps are simple:

1. Calculates the position of the key on the hash table by the hashcode of the key H

2. If the hash table does not exist or the table is empty or the hash table points to the position of H (which is, of course, further computed by H to locate the position) is empty, meaning that there is no value for the key, return null

3. Step 2 is not established, find the location:

The hash value of the first element is the same, then the value of the key is equal, the value is returned equal, and the last while loop is continued to find the hash value equal, the key is equal, and the value is returned. A null pointer exception appears when the key is null.

The hash value of the first element is less than 0, and it is also traversed by the node class itself, which is not much different from the later while step (I do not understand why we should write this step)

To deposit an element:

Final V Putval (K key, V value, Boolean onlyifabsent) {if (key = = NULL | | value = NULL) throw new NULLPOINTEREXCEP        tion ();        int hash = spread (Key.hashcode ());        int bincount = 0; For (node<k,v>[] tab = table;;)            {node<k,v> F; int n, I, FH; if (tab = = NULL | |            (n = tab.length) = = 0) tab = inittable ();                             else if ((f = tabat (tab, i = (n-1) & hash)) = = null) {if (Castabat (tab, I, NULL,                   New node<k,v> (hash, key, value, NULL))) break; No lock when adding to empty bin} else if ((fh = f.hash) = = MOVED) tab = Helptran            Sfer (tab, f);                else {V oldval = null;                            Synchronized (f) {if (Tabat (tab, i) = = f) {if (FH >= 0) {                            Bincount = 1; for (Node<k,v> e = f;;                                ++bincount) {K ek;                                     if (E.hash = = Hash && (ek = e.key) = = Key | | (ek! = null && key.equals (EK))))                                    {oldval = E.val;                                    if (!onlyifabsent) e.val = value;                                Break                                } node<k,v> pred = e;                                                              if ((e = e.next) = = null) {Pred.next = new node<k,v> (hash, key,                                    value, NULL);                                Break                            }}} else if (f instanceof treebin) {       Node<k,v> p;                     Bincount = 2; if (p = ((treebin<k,v>) f). Puttreeval (hash, key, value))!                                = null) {oldval = P.val;                            if (!onlyifabsent) p.val = value;  }}}} if (Bincount! = 0) {if                    (Bincount >= treeify_threshold) treeifybin (tab, i);                    if (oldval! = null) return oldval;                Break        }}} addcount (1L, Bincount);    return null; }

The steps to deposit are relatively complex and will continue to be repeated. The steps are as follows:

1. Table does not exist CREATE table:

The step to create the table is also a dead loop, through the SIZECTL to perform multi-threaded initialization Table control, when the thread priority to get the modification will change this value to 1, other threads can not modify the yield CPU execution, continue to loop attempt to gain the right to modify (if also satisfies the condition of the while loop, The table is null or has a capacity of 0). The table that gets the right to modify uses the default capacity of 16 to create the hash table, the SC is set to 3/4 of the current capacity, and finally assigns it to Sizectl.

2. If the table exists, it will find the location of the table where the key is located, there is no value that means no conflict, the first time setting, through the CAs to try to set, set a successful jump out of the loop, failed does not matter, continue to loop.

3. If the hash of the first element in the specified position is marked as a moved state, the transfer operation is adjusted and then recycled, transfer the following:

The comment on the method also understands that the moved state means that all nodes in the location are in the resize state of movement, and this is dealing with the conflict between the expansion and the put. The table is not null and the node is Forwardingnode and nexttable is not empty, the judgment is in resize, the subsequent calculation principle is not very clear, but still can understand the role of this code. First calculate the rs,resize time nexttable,table and Sizectl are less than 0, is not over, into the cycle in the judgment of the SC and RS relationship and transferindex subscript judgment has not finished processing, the process is out of circulation, If you do not finish, you will seize the process, and eventually return to the transfer of the Nexttab,put method in the resize phase seamlessly linked to the new table. Here the logic is very clear, concurrent put when the Helptransfer may also be called concurrently, we expect to return a new table, but the new table while loop is controlled by sizectl, meaning that the sizectl<0 move is complete, It is not a problem to return a new table, so this value is the last to change, all the other threads will get the new table, and the moved state of the upper layer should be changed later so that there is no problem, all the new elements are entered into the updated table. and meeting the bounce in the loop means the conversion is complete, and these changes should happen earlier. The biggest doubt is that the value of the SC after Rob transfer change, the subsequent will directly return to Nexttab, this time nexttable really ready, that is, transfer operation may be slow, resulting in the actual nexttab is not ready. Otherwise, the sc+1 is still less than 0 and still enters the loop, but multiple threads may operate the Tranfer method at the same time, which can cause a conflict of handling. All the key lies in the realization of the transfer method.

Transfer's code is too long, here is a brief description of its steps:

1. Calculate the value of the stride, the single core is the table length, multicore is the table length/8/the number of cores, the minimum 16, the meaning of this field is to deal with the number of hash barrels at a time.

2. If nexttab==null, create Nexttab, twice times the original length

3. Build the Forwardingnode node, whose hash is the pattern moved, which contains the new table

4. The dead loop begins to transfer the node to the new table:

First loop to find the next processing hash table position. The process is handled backwards, and the later part of the array is processed, and Transferindex indicates the starting position of the next label for the next processing. Stride is how many hash buckets are processed at a time. The way to skip this lookup location is that all nodes have been allocated processing, through the CAS thread Rob processing right, here is a clever multi-threaded segmented processing, each thread does not interfere. As long as the other threads end up waiting for all processing to finish, there is no thread-safety issue.

If the i<0 and other conditions are established, it means that the current thread is not capable of processing, judging the size of the SC, if it conforms to the end of the judgment change and set the finish, the next loop completes the table update. Here it can be seen that the end of the judgment is given to the SC changes, this is the same for all the threads of judgment, the judge does not pass will be directly returned, any thread into the Resize transfer link will make sc+1, all the threads leave will-1, The problem is that only one thread will know that all the processing is done and change the table. ( this leads to the above problem, put in the resize link, the returned table may not be ready for the newtable, but it does not matter, because the transfer process locks the table hash of the first element, the put operation Lock is the same, so the conversion is still completed )

I is the current thread processing hash table subscript, if NULL, set to Forwardingnode, that is, moved mode

Not NULL, but the hash is a moved state, indicating that processing is being processed and the location of the process needs to be re-selected.

Lock the hash table subscript object F, if the hash table subscript F does not change to mean that there is no change, can be transferred. The transferred part is no longer described, and the processing end is selected, and the subscript of the lock processing is sufficient to ensure the thread is safe. By the way, when it is processed, it will change the first element to Forwardingnode,put, knowing that it is being processed and will enter Helptransfer.

4. Lock the current table subscript the first element, and insert the operation. Here is a problem, although the same as the resize link lock is the first element of the table subscript, but will not appear inconsistent situation? Transfer's F calculation is the first of the old table, the first leg of the put link is really an old table, but after helptransfer it becomes a new table, and then the loop is not inconsistent, the new table is still not ready. In fact, because only the subscript processing is finished, will be set to moved state, put link will be cut into a new table, otherwise it will enter the lock link, at this time if you are transferring the content of this interval, will not enter, do not transfer also does not matter, directly into the old table is good, then deal with the time will be treated. And synchronize in put wait transfer complete, do again judge whether the first node is consistent, do not have to worry about inserting the old table, because the new table is completed after the old table that node is the Forwardingnode node, not equal, the next cycle will enter the switch to the new table.

5. Count, not to be described, through Countercell.

Other methods are not described in general, the retrieval method is not locked, the insertion of the removal method considers the problem of expansion, through the clever use of CAs and lock subscript the first object completed, the moved state is converted to complete the hash table, to get a new table directly into the relevant position can be, not completed, Insert the old table directly and wait for the transfer to complete. In fact, there will be a problem, the old table inserted position and the new table hash out the same location? I think the answer is certainly not the same, then it will lead to a new problem, the old table of the hash bucket x moved the new table in each position, but put blocked into a new table, the key value hash out of the different, will fall to the new table location, think again, if the new table scattered elements of the old table, There is a problem with this transfer. So actually the hash method and the general hash is not the same, and the transfer of time is to expand the old table twice times, the old table bucket is also split into two, it should be a certain algorithm to ensure that the bucket element will only fall on the two new barrels, so that the old table added elements will not fall on the other barrels of the new table, The perfect realization of the overall movement of the bucket without breaking the elements, resulting in the entire structure is not available. The calculation principle is not studied in detail.

The Java Collection (25) Concurrenthashmap

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.