The Java Collection (26) Concurrentskiplistmap

Source: Internet
Author: User

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

1. Preface

A scalable concurrency implementation, this map implements the sorting function, the default is to use the CompareTo method of the object itself, if the comparator is provided, the comparator comparison method is used. In short, concurrentskiplistmap is a concurrency implementation of TREEMAP, but why isn't it called Concurrenttreemap? This is related to its own implementation. This class is a variant of the skiplists implementation that provides the time overhead for log (n): ContainsKey, get, put, remove. Operations such as insertion, removal, update, and access are thread-safe. Iterators are weakly consistent, ascending iterators are faster than descending. The map's size method is not a constant time overhead and requires traversal, so this value may not be allowed in concurrency. The map also does not allow null keys or values.

2.concurrentskiplistmap2.1 Implementation principle

This class implements a two-dimensional tree jump linked list, which is represented by a separate node that holds the base node of the data. There are two reasons to take this approach instead of using arrays: 1. Array implementations are more complex, more expensive, and 2. We can use less expensive algorithms to complete a large number of traversed index lists instead of the basic linked list. is a list structure of the underlying two-level index:

The underlying algorithm uses a variant of the HM linked ordered set algorithm. The basic principle of these algorithms is to mark the deletion of the node's next node pointer when the node is deleted, to avoid concurrent insert collisions, and to determine when and how these deleted nodes will be disconnected when traversing the triples (predecessor, current node, successor).

The node directly uses CAs to mark the next pointer instead of marking the list deletion with a tag bit. When deleted, instead of marking a pointer, it is stitched in another node that is considered a marker pointer. In addition to using the delete tag, the list also has empty elements that are considered to be deleted, which is similar to lazy delete mode. If the value of a node is null, it is considered to be tombstoned and ignored. Here is the deletion of a node, the deletion of n nodes, the initial state is as follows:

The value of 1.CAS sets n is changed from non-null to NULL. From this point on, there is no public operation that will assume that the node exists, while other ongoing inserts and deletes may still be changing their next pointer.

The next pointer of 2.CAS sets n is a new tag node, and when this node is present, no other nodes can be added behind N, which is to prevent deletion errors.

3.CAS sets the next pointer to B, crosses N and marker nodes, and at this point, no traversal method can access n, which can be garbage collected.

Failure of the first step causes a simple retry, 2, and 3 steps fail, because other operations ignore the null node and help remove the tombstone node from the list.

2.2 Data structures

is a data structure, the head node of a linked list, a comparator, and an object that has a head node.

Node nodes also compare standards, key values, and the next node, with the following internal methods:

Casvalue:cas set the value of the node

Casnext:cas Set node Next

Ismarker: Determine whether the node is a marker node, based on the value of the marker node is itself

Isbaseheader: Determines whether the node is a head node, according to the head nodes value is the Base_header object of the class

Appendmarker:cas the next node of the set node is the marker node, and the parameter is the node's original next junction.

Helpdelete: Help to delete the node (when the node is value null)

Getvalidvalue: Returns the value of the current node

CreateSnapshot: Creates a key-value pair snapshot of the node, which is a non-changing collection

Index is the data structure of this class, it continues to encapsulate node, more down and right node, this is a jumping table of the basic structure. The method is as follows:

Casright:cas set the right pointer for the node

Indexesdeletednode: Determine if the node has been tombstoned

Link:cas set a new successor node, the parameter is the original successor and the new successor node

Unlink:cas the successor node of the node is set to the subsequent node of that node, which is to remove the successor node of the node

Headindex inherits from index and complements index's missing level field.

2.3 Basic Operations

Gets a key-value pair:

The steps are as follows:

1. Locate the previous Node B of the Jump table key by key, and the key value is after the Node B.

2. If the next node n of B is null, it means that B is the last node, there are no elements to find, jump out of the loop

3. Re-detects if the next node of B is n, does not mean that it was inserted by a put, and that the predecessor node is again recycled

4.N node value is null, tombstoned, helpdelete help remove the node, jump out of the loop, and re-locate the predecessor node

5.B node value is null, or N==n.value (marked node) b is removed, jumping out of the loop, re-looking for the predecessor node

6. Compare the key of n with the obtained key, the return value is equal, and <0 jumps out of the loop. Continue to judge N.next without finding it.

Find the Skip table predecessor node method where the specified key begins to traverse as follows:

1. Start the loop from the beginning, and the right node of the current nodes is R.

2.R is not NULL, but the value is null, attempting to remove, removing the failure to resume the traversal from head, successfully continuing to find the next hop, continue to traverse. If the R value is not NULL, but the value of the key is larger, it means that you can skip the paragraph and continue looking for the next hop.

3. Find the right jumping point, go to the starting node of the jumping point, down exists is to the current point of jumping nodes, exist in the down to find the right jumping point.

If you have doubts about this structure, you can refer to: here. To understand what a jump table is.

Put an element:

    Private V DoPut (K key, V value, Boolean onlyifabsent) {node<k,v> z;        Added node if (key = = null) throw new NullPointerException (); comparator<?        Super K> CMP = comparator; Outer:for (;;) {for (node<k,v> B = findpredecessor (key, CMP), n = b.next;;)                    {if (n! = null) {Object v; int c;                    node<k,v> f = n.next;                    if (n! = B.next)//inconsistent read break;                        if ((v = n.value) = = null) {//n is deleted n.helpdelete (b, f);                    Break                    } if (B.value = = NULL | | v = = n)//b is deleted break;                        if ((c = CPR (CMP, key, N.key)) > 0) {b = n;                        n = f;                    Continue                 }   if (c = = 0) {if (Onlyifabsent | | n.casvalue (v, value)) {@SuppressWa                            Rnings ("unchecked") v vv = (v) v;                        return VV; } break; Restart if lost race to replace value}//Else C < 0;                Fall through} z = new node<k,v> (key, value, N);         if (!b.casnext (n, z)) break;            Restart if lost race to append-B break outer;        }} int rnd = Threadlocalrandom.nextsecondaryseed ();            if (rnd & 0x80000001) = = 0) {//test highest and lowest bits int level = 1, max;            while ((Rnd >>>= 1) & 1)! = 0) ++level;            Index<k,v> idx = null;            Headindex<k,v> h = head; if (level <= (max = H.level)) {for (int i = 1; I <=Level            ++i) idx = new Index<k,v> (z, idx, NULL);  } else {//try to grow by one, level = max + 1,//hold in array and later pick the one to Use @SuppressWarnings ("unchecked") index<k,v>[] Idxs = (index<k,v>[]) New Ind                ex<?,? >[level+1];                for (int i = 1; I <= level; ++i) Idxs[i] = idx = new Index<k,v> (z, idx, NULL); for (;;)                    {h = head;                    int oldlevel = H.level;                    if (level <= oldlevel)//Lost Race to add level break;                    headindex<k,v> NEWH = h;                    node<k,v> oldbase = H.node; for (int j = oldlevel+1; J <= level; ++j) NEWH = new Headindex<k,v> (oldbase, NEWH, Idxs[j]                    , j);  if (Cashead (h, NEWH)) {h = NEWH;                      IDX = Idxs[level = Oldlevel];                    Break }}}//Find insertion points and splice in splice:for (int Insertionlev El = level;;)                {int j = H.level; for (index<k,v> q = h, r = q.right, t = idx;;)                    {if (q = = NULL | | t = NULL) break splice;                        if (r! = null) {node<k,v> n = r.node;                        Compare before deletion check avoids needing recheck int c = CPR (CMP, key, N.key);                            if (N.value = = null) {if (!q.unlink (R)) break;                            R = q.right;                        Continue                            } if (C > 0) {q = r;             R = r.right;               Continue                            }} if (j = = Insertionlevel) {if (!q.link (r, T)) Break                            Restart if (T.node.value = = null) {FindNode (key);                        Break splice;                    } if (--insertionlevel = = 0) break splice;                    } if (--j >= insertionlevel && J < level) T = T.down;                    Q = Q.down;                R = q.right;    }}} return null; }

The Put method has undergone 2 main steps:

1: Find the appropriate location and insert the node.

1) Find the front jump point B, its next node is N,

2) Traverse to find the appropriate insertion point, n is null to create the node, add the next node in B, add successful jump out of the first step, failure to re-1)

3) n is not NULL, it is to find the node should be inserted, first to determine whether N or B's next node, to prevent being preemptive in the middle of the insertion, and then determine whether the n node is a valid node, the logic deleted back to 1) and then again. Finally determine if the B node is deleted. Later if the size of the key is greater than the K-node, it means to look back, if it is equal to replace the value of the node, jump out the first step. Finally find the right insertion point to try to insert, fail again, the successful end of the first step. The logic of the whole process is similar to get.

2: Build the node of the jumping table, adjust the jump table. The first step is to simply insert the node into the list, and you need to complete the form of the jump table. (level means to skip the table interval, the higher the level of the same level of nodes, the greater the interval, this way in the search can increase the search speed, starting from the largest level, step-by-step location node)

1) random level, even and greater than 0. Random methods are not explained.

2) If the level is smaller than the head node, generate a series of head node down nodes (the index node contains node, which is naturally the node inserted in step 1), starting at level 1

3) This level is higher than the head node level, increasing one level, generating all level nodes starting from 1 (node is the insertion node) to form a down chain.

4) Judge the head node level again, if the head level is higher than this level, the proof is the preemptive adjustment, again. Without preemption, rebuilding the head node index Headindex,node is the node of the head node, which complements the missing level. Replace the head node Headindex successfully jump out of the loop, failed again.

These are the nodes that construct the down direction, ensuring that the down direction of the head contains all index levels. The next method is to build a connection to the right method. Notice here that H becomes the new head node, and level is the old one.

5) H node or H's right node R is null, no need to proceed, end the link.

6) R is not NULL, compare key and R node N's key,n nodes are tombstoned, help them to remove, remove and find the next R node. If the current r node is less than key, then key is still on the right, continue to find R. Until you find out where key should be, the R node >=key,key right is R.

7) continuously downgrade until the current insertion level is found until the connection is reached at the specified level, the connection fails again, and if the build node is tombstoned, delete it by Findnode method.

The whole process is somewhat abstract, combined with two-dimensional graph to see more clearly, first of all, one-dimensional ordered linked list, this is node node, but to speed up the search speed, using the retrieval level Indexlevel constitute a two-dimensional diagram. As mentioned before, the higher the indexlevel level, the greater the interval, the fewer nodes. A new add knot, first to determine its level, 1 levels do not need to build Indexnode, a series of judging its own level, the first to build a series of down direction of the node, and then through the head node, the entire right direction node Unicom, this is a basic idea. The head node must have the highest level due to the traversal from the beginning of the node. So when the new node basically exceeds the head node, the head node level should be raised. This is the general logic.

Other methods are no longer introduced, which basically can understand the basic principles of concurrentskiplistmap.

The Java Collection (26) Concurrentskiplistmap

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.