Before we learn concurrentskiplistmap we need to learn a randomized data structure-jump Table (skip list)
There are many ways to find an array, if it is ordered, you can use a binary lookup, binary lookup requirements elements can be randomly accessed, so that the need to store the elements in contiguous memory. This is really quick to find, but when inserting and deleting elements, a lot of moving elements are needed to ensure the order of elements. For a linked list, can not be random access, that is, can not simply use the binary search, only through sequential traversal of the way, in order to make the linked list can also have good query performance, it is derived from the jump table this data structure, and jump table compared to the balance tree, its implementation is relatively simple many. Introduction to jump Table
Jump Table (skiplist) is a random data structure, jump table in an orderly way in the hierarchical chain of the elements, efficiency and balance tree comparable to-find, delete, add, etc. can be done in logarithmic expected time, and compared to the balance tree, the realization of the jump table is much simpler and more intuitive, The jump table can be intuitively understood by the following illustration.
The above picture is an example of a jump table, let's talk about the construction feature of the jump table: a jump table should have several layers (level) linked list; The bottom-most list in the Jump table contains all the data, the reference of the data stored in the upper-list, and the data in the jump table is orderly; The head pointer points to the first element of the highest layer;
In this way, the establishment of multi-layer linked list, starting from the top to find data, to achieve a jump query data, the use of space in exchange for time, the following together to see the establishment of the jump table and query process. Lookup of Jump table
SKIPLISTD search algorithm is simpler, for the above we want to find element 42, the process is as follows: larger than 6, looking back (20), 20 after no data, enter 20 of the next layer than 20, continue looking backward, find 42.
Insert of Jump table
Why is a jump table a random data structure, because each time you add data, it will randomly determine whether the data can climb to a high-level list, that is, the same data constructed by the jump table may be different, the process we look at the following diagram:
Add Data
Add Data 42:
First, you look for the 42 precursor nodes that should be inserted into the location. Start looking at the node in the head (right, then left), when you find the node 20 o'clock, there is no node behind, then the next layer to find, then you will find the node 42 of the precursor should be 30 this node, The data is then inserted into the bottommost list:
Then the random process determines whether node 42 will climb like above and determine the level of climbing, assuming that there is a need to climb up two layers, the results are as follows:
Connection Index Layer
Of course this is not the end, now we have to insert data into the list, while generating the index layer, then another step, is to connect the index layer
Skip Table Deletion
Jump table deletion is actually similar to inserting, first find the node, and then remove each layer of the link.
At this point on the jump table should have a certain understanding of the following to see how the JDK Concurrentskiplistmap is how to achieve the jump table, combined with specific analysis, can also enhance understanding. Concurrentskiplistmap (JDK 1.8)
Concurrentskiplistmap a concurrent security, based on skip list to achieve ordered storage Map,concurrentskiplistmap provides three internal classes to build such a linked list structure: Node, Index, Headindex. Where node represents the lowest level of a single linked list of ordered nodes, index represented as a node based index layer, Headindex used to maintain the index hierarchy. Inheritance System
Data Structure
Node nodes definition:
Static Final class Node<k,v> {
final K key;
volatile Object value;
Volatile node<k,v> next;
/**
* Creates a new regular node.
*
/Node (K key, Object value, node<k,v> next) {
this.key = key;
This.value = value;
This.next = next;
..//Omit partial method
}
Index definition:
Static class Index<k,v> {
final node<k,v> Node; The data node references
final index<k,v> down;//Lower index
volatile index<k,v> right;//Right-hand index
/**
* Creates index node with given values.
* *
Index (node<k,v> node, index<k,v> down, index<k,v> right) {
this.node = node;
This.down = down;
This.right = right;
.../Omit part of code
}
Headindex definition:
/**
* Nodes heading level keep track of their.
* *
static final class Headindex<k,v> extends index<k,v> {
final int level;//index layer, starting from 1, node single strand surface is 0
Headindex (node<k,v> node, index<k,v> down, index<k,v> right, int level) {
Super (node, down, right);
This.level = level;
}
Headindex adds a level attribute to indicate the index hierarchy; Note that all Headindex point to the same Base_header node;
/**
* Special value used to identify Base-level header
/
private static final Object Base_header = new OBJ ECT ();
/**
* The topmost head index of the skiplist.
* * Private transient volatile headindex<k,v> head;//Headindex header pointer
/**
* Comparator used to Mai Ntain order in this map, or null if
* using natural ordering. (Non-private to simplify access in
* nested classes.)
* @serial
/Final comparator< super k> Comparator; Element comparer
Above is the definition of the jump table in Concurrentskiplistmap, but still more abstract, or converted to a better understanding of the diagram bar:
Note : In the simple diagram of the jump table above, no headindex structure is drawn .
1. Default Construction
/**
* Constructs a new, empty map sorted according to the
* {@linkplain comparable natural ordering} of the keys.
* * Public
Concurrentskiplistmap () {
this.comparator = null;
Initialize ();
}
2. Specify comparator
/**
* Constructs a new, empty map, sorted according to the specified
* comparator.
* * Public
concurrentskiplistmap (comparator< super k> Comparator) {
this.comparator = Comparator;
Initialize ();
}
3, initialization through the collection
/**
* Constructs a new map containing the same mappings as the given map,
* Sorted according to the {@linkplain Co Mparable Natural Ordering} of
* the keys.
* * Public
concurrentskiplistmap (map< extends K,? extends v> m) {
this.comparator = null;
Initialize ();
Putall (m);
}
/**
* Constructs a new map containing the same mappings and using the
* Same ordering as the specified MA P.
* * Public
Concurrentskiplistmap (sortedmap<k,? extends v> m) {
this.comparator = M.comparator ();
Initialize ();
Buildfromsorted (m);
}
The Initialize () method is called in the constructor method
private void Initialize () {
keyset = null;
EntrySet = null;
values = null;
Descendingmap = null;
Initialize head head
= new headindex<k,v> (new node<k,v> (null, Base_header, NULL),
null, NULL, 1);
}
The initially created jump table structure is as follows:
Add data (Put)
Public V-Put (K key, V value) {
if (value = = null)
throw new NullPointerException ();
Return DoPut (key, value, false);
}
Requires value not to be empty, internal call doput method. Findpredecessor Method
The function of the Findpredecessor method is to look for the precursor of a key (if you encounter a node that needs to be deleted, then make a secondary deletion). Start at the top of the headindex to the right one step at a time, until the right is null or the node key of the right-hand nodes is greater than the current key, and then look down again, repeating the process in turn until the down is null, where the precursor is found.
Private node<k,v> Findpredecessor (Object key, comparator<. Super K> CMP) {if (key = null) throw New NullPointerException (); Don ' t postpone errors for (;;) {//From Head Start traversal for (index<k,v> q = head, R = q.right, D;;)
{//R!= NULL, which indicates that there are nodes to the right of the node and needs to compare if (R!= null) {node<k,v> n = r.node;
K k = N.key;
Value = = NULL, indicating that the node has been deleted//deleted by unlink () if (N.value = = null) { if (!q.unlink (R)) break; Restart R = q.right;
Reread R continue;
//If key greater than R node continues to traverse if (CPR (CMP, key, K) > 0) {q = r;
R = r.right;
Continue
}//If DOWM = NULL indicates that the pointer has reached the lowest level, return the node directly if ((d = q.down) = = null) return q.node;
Otherwise enter the lower level to find q = D;
R = d.right; }
}
} DoPut Method
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 (;;) {//b is the front relay node, n is the next for the forward node (node<k,v> B = findpredecessor (key, CMP), n = b.next;;)
{if (n!= null) {//b is the last node of the list Object v; int c;
node<k,v> f = n.next;
Under multithreading there is a competition if (n!= b.next)//inconsistent read break; Node n has been tombstone, for auxiliary physical deletion if ((v = n.value) = = null) {//n is deleted N.helpdele
Te (b, f);
Break
} if (B.value = null | | | v = n)//b is deleted break;
node is greater than, continue to look for if (c = CPR (CMP, key, N.key) > 0) {b = n;
n = f;
Continue //equal, depending on the parameter onlyifabsent decide whether to overwrite value if (c = = 0) {if (Onlyifabsent | |
N.casvalue (V, value)) {@SuppressWarnings ("unchecked") v vv = (v) v;
return VV; ///failure to compete; Restart if lost race to replace value}/else c < 0;
Fall through}//create node z = new Node<k,v> (key, value, N); Insert a node, and if it fails, a repeat if (!b.casnext (n, z)) break;
Restart if lost race to append to B-break outer;
}///random number int rnd = Threadlocalrandom.nextsecondaryseed ();
Determine if you need to add level if ((rnd & 0x80000001) = = 0) {//test highest and lowest bits int level = 1, max; Gets the level while ((RND)>>= 1) & 1)!= 0) ++level;
Index<k,v> idx = null;
Headindex<k,v> h = head;
If the hierarchy level is greater than the maximum level, a new layer is required, otherwise the node is added to the hierarchy and to the level below it. Level is smaller than the highest head.level, directly generating the required index if (levels <= (max = H.level)) {for (int i = 1; I <= level ;
++i)//generate Index idx = new Index<k,v> (z, idx, NULL);
else {//level > Max level = max + 1;//hold in array and later pick the "one" use @SuppressWarnings ("Unchecked") index<k,v>[] Idxs = (index<k,v>[)) New index<?,? >[level+1
];
for (int i = 1; I <= level; ++i)//Generate Index idxs[i] = idx = new Index<k,v> (z, idx, NULL); for (;;)
{h = head;
int oldlevel = H.level; The hierarchy expands and needs to be restarted (other threads have changed the jump table) if (level <= oldlevel)//Lost race to add levels BReak;
headindex<k,v> NEWH = h;
node<k,v> oldbase = H.node; Generate a new Headindex node for (int j = oldlevel+1 J <= level; ++j) NEWH = Newer HEADINDEX&L T
K,v> (Oldbase, NEWH, Idxs[j], J);
Update head if (Cashead (h, NEWH)) {h = NEWH;
IDX = Idxs[level = Oldlevel];
Break
The index layer was generated before/** *, but did not insert these indices into the corresponding hierarchy * the following code is to link the index to the corresponding layer ///////start splice:for (int insertionlevel = level;;)
{int j = H.level; Starting with Headindex for (index<k,v> q = h, r = q.right, t = idx;;)
{if (q = = NULL | | t = NULL) break splice; R!= Null; This is to find the appropriate level of insertion node position, note here only to look for if (R!= null) {node<k,v> n = r.node;
Compare before deletion check avoids needing int c = CPR (CMP, key, recheck);
Need to delete r if (N.value = = null) {if (!q.unlink (R))
Break R = q.right;
continue to continue backwards;
///Right to traverse if (C > 0) {q = r;
R = r.right;
Continue The location where the node is to be inserted is found above, where the if (j = = Insertionlevel) {/ /establish link, failure retry if (!q.link (r, T)) break;
Restart if (T.node.value = = null) {Findnode (key);//lookup node, delete node to be deleted during lookup
Break splice;
}//Link complete if (--insertionlevel = = 0) break splice;
Continue link to other index layer if (--j >= insertionlevel && J < level)
t = T.down;
Q = Q.down;
R = q.right;
}} return null; }
Doput method code is longer, to comb the logic:
1, through the Findpredecessor () method to confirm key to insert position
2, data validation, if you find that you need to delete the node, then the secondary removal, if the other thread changed the jump table, then retry or traverse to find the appropriate location.
3, if the key already exists in the Jump table, determine whether to overwrite the old value according to Onlyifabsent.
4, the Generation node, inserted into the bottom of the data linked list.
5, according to the random value to determine whether to create an index layer, if not required to return, otherwise perform step 6th
6. If you need to create an index layer that exceeds the maximum level, you need to create the Headindex index layer, otherwise you only need to create the index layer.
7, starting from the head to traverse, the new added index layer of each layer to connect (this can be combined with the above Jump table link index layer diagram to understand). Find Data
Public V get (Object key) {return
doget (key);
}
Private V doget (Object key) {if (key = = null) throw new NullPointerException (); comparator<?
Super K> CMP = comparator; Outer:for (;;) {//Find its predecessor node for (node<k,v> B = findpredecessor (key, CMP), n = B.next by findpredecessor method;;)
{Object v; int c;
if (n = = null)//does not exist the key break outer;
node<k,v> f = n.next;
Other threads updated the jump table, retrying if (n!= b.next)//inconsistent read break;
Need to delete data if ((v = n.value) = = null) {//n is deleted n.helpdelete (b, f);//assist in deleting
Break
//b will be deleted, repeat if (B.value = = NULL | | | = = n)//b is deleted break;
Found the if ((c = CPR (CMP, key, n.key) = = 0) {@SuppressWarnings ("unchecked") v vv = (v) v;
return VV; } if (C <0)//does not exist the key break outer;
Other threads have added data, and continue traversing backward to find B = n;
n = f;
} return null; }
Find the data is relatively simple, first through the findpredecessor to find its predecessor, and then along the right to find it, and in this process, if you find that a node needs to be deleted, you need to be assisted deletion, if the Jump table data structure is found by other threads change, Will try to get its predecessor again. Delete Data
Concurrentskiplistmap supports concurrent operations, so it is important to note when deleting, because other threads may be inserting data at that location at the same time, which can easily result in the loss of data, which we have in front of the blocking queue Synchronousqueue A similar problem is encountered in Synchronousqueue, where a cleanme tag is used to mark the precursor of a node that needs to be deleted, and a similar mechanism in CONCURRENTSKIPLISTMAP is to add a special node after the deletion to mark , and then the overall deletion, if not marked, then if the node is being deleted, other threads may be adding data behind this node, resulting in data loss.
Public V-Remove (Object key) {return
doremove (key, NULL);
}
Call the Doremove () method, Doremove has two parameters, one is key, and the other is value, so the Doremove method provides the remove key and also satisfies the key-value.
Specify key and value to delete the corresponding node final V doremove (object key, object value) {if (key = = null) throw new NULLPOINTEREXCEP
tion (); comparator<?
Super K> CMP = comparator; Outer:for (;;) {//Find its predecessor for (node<k,v> B = findpredecessor (key, CMP), n = b.next;;)
{Object v; int c;
if (n = = null)//does not exist the key break outer;
node<k,v> f = n.next;
Other threads modified the jump table data structure if (n!= b.next)//inconsistent read break; node n needs to be deleted, to assist in deletion, and then retry if ((v = n.value) = = null) {//n is deleted N.helpdelete
(b, f);
Break
//b will also be deleted if (B.value = = NULL | | | = = n)//b is deleted break;
There is no this key if (c = CPR (CMP, key, N.key) < 0) break outer;
if (C > 0) {//Continue traversal lookup backward b = n;
n = f;
Continue //key equals, value is not equal, exit if (value!= null &&!value.equals (v)) break outer
;
Logical deletion, setting Value=null if (!n.casvalue (V, null)) break; Add a delete tag before deleting the IF (!n.appendmarker (f) | |!b.casnext (n, f)) Findnode (key); Retry via Findnode else {//Clear index layer Findpredecessor (key, CMP); Clean index//The layer has no nodes, delete the layer if (head.right = = null) tryreducelevel
(); } @S