Java concurrency programming Summary 4 -- ConcurrentHashMap improvement in jdk1.8, concurrenthashmap

Source: Internet
Author: User

Java concurrency programming Summary 4 -- ConcurrentHashMap improvement in jdk1.8, concurrenthashmap

I. a brief review of the design of ConcurrentHashMap in jdk1.7

First, let's take a look at the design of the ConcurrentHashMap class in jdk1.7. Its basic structure is as follows:

Each segment is a HashEntry <K, V> [] table. Each element in the table is essentially a one-way queue of HashEntry. For example, table [3] is the first node, table [3]-> next is node 1, followed by node 2, and so on.

Public class ConcurrentHashMap <K, V> extends AbstractMap <K, V> implements ConcurrentMap <K, V>, Serializable {// divide the entire hashmap into several small maps, each segment is a lock. Compared with hashtable, this design aims to reduce concurrency conflicts for put, remove, and other operations, you can perform concurrent operations on a node that does not belong to the same Segment, greatly improving the performance of final Segment <K, V> [] segments; // essentially, the Segment class is a small hashmap, the table array stores the data of each node and inherits ReentrantLock. It can be used as a mutual lock to use static final class Segment <K, V> extends ReentrantLock implements Serializable {transient volatile HashEntry <K, v> [] table; transient int count;} // basic node, storage Key, Value static final class HashEntry <K, V> {final int hash; final K key; volatile V value; volatile HashEntry <K, V> next ;}}

 

2. Improvements in jdk1.8

Improvement 1: cancels the segments field and directly uses transient volatile HashEntry <K, V> [] table to store data and uses the table array element as the lock, thereby locking each row of data, further reduce the probability of concurrency conflicts.

Improvement 2: change the data structure of the original table array + one-way linked list to the table array + one-way linked list + red/black tree structure. For hash tables, the core capability is to evenly distribute keys in arrays after hash. If the hash is uneven, the length of each queue in the table array is mainly 0 or 1. However, the actual situation is not always so ideal. Although the default loading Factor of the ConcurrentHashMap class is 0.75, there are still some cases where the queue length is too long when the data volume is too large or the luck is poor, if one-way list is used, the time complexity of querying a node is O (n). Therefore, for a list with more than 8 nodes (default, the structure of the red/black tree is adopted in JDK, so the query time complexity can be reduced to O (logN), which can improve the performance.

To illustrate the above two changes, let's take a look at how the put operation is implemented.

Final V putVal (K key, V value, boolean onlyIfAbsent) {if (key = null | value = null) throw new NullPointerException (); int hash = spread (key. hashCode (); int binCount = 0; for (Node <K, V> [] tab = table;) {Node <K, V> f; int n, I, fh; // initialize the table if it is empty. Otherwise, the array index I is calculated based on the hash value. If tab [I] is empty, create a Node directly. Note: tab [I] is essentially the first node of the linked list or red/black tree. 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} // If the tab [I] is not empty and the hash value is MOVED, the linked list is performing the transfer operation, return the table after resizing. Else if (fh = f. hash) = MOVED) tab = helpTransfer (tab, f); else {V oldVal = null; // lock the first node instead of segment, further reduce thread conflicts synchronized (f) {if (tabAt (tab, I) = f) {if (fh> = 0) {binCount = 1; for (Node <K, v> e = f; ++ binCount) {K ek; // If the node e with the value of key is found in the linked list, set e directly. val = value. If (e. hash = hash & (ek = e. key) = key | (ek! = Null & key. equals (ek) {oldVal = e. val; if (! OnlyIfAbsent) e. val = value; break;} // if no Node with the key value is found, create a Node and add it to the linked list. Node <K, V> pred = e; if (e = e. next) = null) {pred. next = new Node <K, V> (hash, key, value, null); break ;}}// if the first Node is of the TreeBin type, the tree structure is red and black, perform the putTreeVal operation. 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 the number of nodes> = 8, convert the linked list structure to a red-black tree structure. If (binCount> = TREEIFY_THRESHOLD) treeifyBin (tab, I); if (oldVal! = Null) return oldVal; break ;}}// the count is increased by 1, which may trigger the transfer operation (expansion ). AddCount (1L, binCount); return null ;}

In addition, there are also some minor improvements in other aspects, such as the addition of the field transient volatile CounterCell [] counterCells; the number of all elements in the hashmap can be conveniently calculated, the performance is much better than the size () method in jdk1.7.

 

Iii. Performance Comparison of ConcurrentHashMap jdk1.7 and jdk1.8

The test procedure is as follows:

public class CompareConcurrentHashMap {    private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(40000);    public static void putPerformance(int index, int num) {        for (int i = index; i < (num + index) ; i++)            map.put(String.valueOf(i), i);    }public static void getPerformance2() {        long start = System.currentTimeMillis();        for (int i = 0; i < 400000; i++)            map.get(String.valueOf(i));        long end = System.currentTimeMillis();        System.out.println("get: it costs " + (end - start) + " ms");    }    public static void main(String[] args) throws InterruptedException {        long start = System.currentTimeMillis();        final CountDownLatch cdLatch = new CountDownLatch(4);        for (int i = 0; i < 4; i++) {            final int finalI = i;            new Thread(new Runnable() {                public void run() {                    CompareConcurrentHashMap.putPerformance(100000 * finalI, 100000);                    cdLatch.countDown();                }            }).start();        }        cdLatch.await();        long end = System.currentTimeMillis();        System.out.println("put: it costs " + (end - start) + " ms");        CompareConcurrentHashMap.getPerformance2();    }}

After running the program for multiple times, the average value is obtained. The result is as follows:

 

Iv. Performance Analysis of Collections. synchronizedList and CopyOnWriteArrayList

When the thread changes the CopyOnWriteArrayList, it copies a new array to store new fields, so the write operation performance is poor. synchronizedList adopts synchronized for read operations, so the read performance is poor. The following is the test procedure:

public class App {    private static List<String> arrayList = Collections.synchronizedList(new ArrayList<String>());    private static List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<String>();    private static CountDownLatch cdl1 = new CountDownLatch(2);    private static CountDownLatch cdl2 = new CountDownLatch(2);    private static CountDownLatch cdl3 = new CountDownLatch(2);    private static CountDownLatch cdl4 = new CountDownLatch(2);    static class Thread1 extends Thread {        @Override        public void run() {            for (int i = 0; i < 10000; i++)                arrayList.add(String.valueOf(i));            cdl1.countDown();        }    }    static class Thread2 extends Thread {        @Override        public void run() {            for (int i = 0; i < 10000; i++)                copyOnWriteArrayList.add(String.valueOf(i));            cdl2.countDown();        }    }    static class Thread3 extends Thread1 {        @Override        public void run() {            int size = arrayList.size();            for (int i = 0; i < size; i++)                arrayList.get(i);            cdl3.countDown();        }    }    static class Thread4 extends Thread1 {        @Override        public void run() {            int size = copyOnWriteArrayList.size();            for (int i = 0; i < size; i++)                copyOnWriteArrayList.get(i);            cdl4.countDown();        }    }    public static void main(String[] args) throws InterruptedException {        long start1 = System.currentTimeMillis();        new Thread1().start();        new Thread1().start();        cdl1.await();        System.out.println("arrayList add: " + (System.currentTimeMillis() - start1));        long start2 = System.currentTimeMillis();        new Thread2().start();        new Thread2().start();        cdl2.await();        System.out.println("copyOnWriteArrayList add: " + (System.currentTimeMillis() - start2));        long start3 = System.currentTimeMillis();        new Thread3().start();        new Thread3().start();        cdl3.await();        System.out.println("arrayList get: " + (System.currentTimeMillis() - start3));        long start4 = System.currentTimeMillis();        new Thread4().start();        new Thread4().start();        cdl4.await();        System.out.println("copyOnWriteArrayList get: " + (System.currentTimeMillis() - start4));    }}

The result is as follows:

 

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.