zoukankan      html  css  js  c++  java
  • Java并发包探秘 (一) ConcurrentLinkedQueue

    本文是Java并发包探秘的第一篇,旨在介绍一下Java并发容器中用的一些思路和技巧,帮助大家更好的理解Java并发容器,让我们更好的使用并发容器打造更高效的程序。本人能力有限,错误难免。希望及时指出。

    Java并发包中有很多精心设计的高并发容器。有ConcurrentHashMapConcurrentSkipListMapConcurrentLinkedQueue等。ConcurrentLinkedQueue就是其中设计最为优雅的高并发容器。它被设计成了无锁的、无界的、非阻塞式的单向链表结构。现在就让我们来一步一步揭开他们神秘的面纱。

    G+

    正文开始:

    一说到链表结构,我们首先就会想到的就是组成链表结构的原件,那就是节点。或者有的人称之为元素。ConcurrentLinkedQueue(为了叙述方便后面用CLQ指代)中称之为Node.

    我们先来看看CLQ中Node的结构:

    Java代码 复制代码 收藏代码
    1. private static class Node<E> {   
    2.         private volatile E item;   
    3.         private volatile Node<E> next;   
    4.   
    5.         private static final  
    6.             AtomicReferenceFieldUpdater<Node, Node>   
    7.             nextUpdater =   
    8.             AtomicReferenceFieldUpdater.newUpdater   
    9.             (Node.class, Node.class, "next");   
    10.         private static final  
    11.             AtomicReferenceFieldUpdater<Node, Object>   
    12.             itemUpdater =   
    13.             AtomicReferenceFieldUpdater.newUpdater   
    14.             (Node.class, Object.class, "item");   
    15.   
    16.         Node(E x) { item = x; }   
    17.   
    18.         Node(E x, Node<E> n) { item = x; next = n; }   
    19.   
    20.         E getItem() {   
    21.             return item;   
    22.         }   
    23.   
    24.         boolean casItem(E cmp, E val) {   
    25.             return itemUpdater.compareAndSet(this, cmp, val);   
    26.         }   
    27.   
    28.         void setItem(E val) {   
    29.             itemUpdater.set(this, val);   
    30.         }   
    31.   
    32.         Node<E> getNext() {   
    33.             return next;   
    34.         }   
    35.   
    36.         boolean casNext(Node<E> cmp, Node<E> val) {   
    37.             return nextUpdater.compareAndSet(this, cmp, val);   
    38.         }   
    39.   
    40.         void setNext(Node<E> val) {   
    41.             nextUpdater.set(this, val);   
    42.         }   
    43.   
    44.     }  
    1. private static class Node<E> {  
    2.         private volatile E item;  
    3.         private volatile Node<E> next;  
    4.   
    5.         private static final  
    6.             AtomicReferenceFieldUpdater<Node, Node>  
    7.             nextUpdater =  
    8.             AtomicReferenceFieldUpdater.newUpdater  
    9.             (Node.class, Node.class, "next");  
    10.         private static final  
    11.             AtomicReferenceFieldUpdater<Node, Object>  
    12.             itemUpdater =  
    13.             AtomicReferenceFieldUpdater.newUpdater  
    14.             (Node.class, Object.class, "item");  
    15.   
    16.         Node(E x) { item = x; }  
    17.   
    18.         Node(E x, Node<E> n) { item = x; next = n; }  
    19.   
    20.         E getItem() {  
    21.             return item;  
    22.         }  
    23.   
    24.         boolean casItem(E cmp, E val) {  
    25.             return itemUpdater.compareAndSet(this, cmp, val);  
    26.         }  
    27.   
    28.         void setItem(E val) {  
    29.             itemUpdater.set(this, val);  
    30.         }  
    31.   
    32.         Node<E> getNext() {  
    33.             return next;  
    34.         }  
    35.   
    36.         boolean casNext(Node<E> cmp, Node<E> val) {  
    37.             return nextUpdater.compareAndSet(this, cmp, val);  
    38.         }  
    39.   
    40.         void setNext(Node<E> val) {  
    41.             nextUpdater.set(this, val);  
    42.         }  
    43.   
    44.     }  



    1.CLQ中的Node定义成了私有的静态类说明该节点描述只适用在CLQ中。
    2.其中用到了AtomicReferenceFieldUpdater原子属性引用原子更新器。该类是抽象的,但该类的内部已经给出了包访问控制级别的一个实现AtomicReferenceFieldUpdaterImpl,原理是利用反射将一个被声明成 volatile 的属性通过Java native interface (JNI)调用,使用cpu指令级的命令将一个变量进行更新,该操作是原子的。atomic 包中还有很多类似的更新器分别针对不同的类型进行原子级别的比较更新原子操作。这里用到了sun.misc.Unsafe 的 compareAndSwap操作(简称CAS)它有三种不同的本地命令分别针对Int、Long、Object进行原子更新操作。
    3.我们可以看出CLQ中的Node结构是一个单向的链表结构,因为每个Node只有一个向后的next和一个item用来装内容。CLQ将通过casNext和casItem方法来原子更新Node链的结构。setNext 和setItem则是直接放入

    我们再来看CLQ的链结构

    Java代码 复制代码 收藏代码
    1. private static final  
    2.         AtomicReferenceFieldUpdater<ConcurrentLinkedQueue, Node>   
    3.         tailUpdater =   
    4.         AtomicReferenceFieldUpdater.newUpdater   
    5.         (ConcurrentLinkedQueue.class, Node.class, "tail");   
    6.     private static final  
    7.         AtomicReferenceFieldUpdater<ConcurrentLinkedQueue, Node>   
    8.         headUpdater =   
    9.         AtomicReferenceFieldUpdater.newUpdater   
    10.         (ConcurrentLinkedQueue.class,  Node.class, "head");   
    11.   
    12.     private boolean casTail(Node<E> cmp, Node<E> val) {   
    13.         return tailUpdater.compareAndSet(this, cmp, val);   
    14.     }   
    15.   
    16.     private boolean casHead(Node<E> cmp, Node<E> val) {   
    17.         return headUpdater.compareAndSet(this, cmp, val);   
    18.     }   
    19.   
    20.   
    21.     /**  
    22.      * Pointer to header node, initialized to a dummy node.  The first  
    23.      * actual node is at head.getNext().  
    24.      */  
    25.     private transient volatile Node<E> head = new Node<E>(null, null);   
    26.   
    27.     /** Pointer to last node on list **/  
    28.     private transient volatile Node<E> tail = head;  
    1. private static final  
    2.         AtomicReferenceFieldUpdater<ConcurrentLinkedQueue, Node>  
    3.         tailUpdater =  
    4.         AtomicReferenceFieldUpdater.newUpdater  
    5.         (ConcurrentLinkedQueue.class, Node.class, "tail");  
    6.     private static final  
    7.         AtomicReferenceFieldUpdater<ConcurrentLinkedQueue, Node>  
    8.         headUpdater =  
    9.         AtomicReferenceFieldUpdater.newUpdater  
    10.         (ConcurrentLinkedQueue.class,  Node.class, "head");  
    11.   
    12.     private boolean casTail(Node<E> cmp, Node<E> val) {  
    13.         return tailUpdater.compareAndSet(this, cmp, val);  
    14.     }  
    15.   
    16.     private boolean casHead(Node<E> cmp, Node<E> val) {  
    17.         return headUpdater.compareAndSet(this, cmp, val);  
    18.     }  
    19.   
    20.   
    21.     /** 
    22.      * Pointer to header node, initialized to a dummy node.  The first 
    23.      * actual node is at head.getNext(). 
    24.      */  
    25.     private transient volatile Node<E> head = new Node<E>(null, null);  
    26.   
    27.     /** Pointer to last node on list **/  
    28.     private transient volatile Node<E> tail = head;  



    1.实际上经过对Node的分析。CLQ中的头尾指针的更新原理其实也是一样的。都是通过cpu原子操作命令进行的更新。

    2.这样我们就有了在高并发下原子更新的基础支持,但是除了原子更新的支持是不够的。原因很简单,这是因为当多个线程同时使用原子更新操作来更新一个链表结构的时候只有一个成功其它的都会失败。失败的操作如何再让它成功才是问题的关键。CLQ优雅的解决了这一问题。

    我们再来看看CLQ的放入元素操作:

    Java代码 复制代码 收藏代码
    1. public boolean offer(E e) {   
    2.         if (e == null) throw new NullPointerException();   
    3.         Node<E> n = new Node<E>(e, null);   
    4.         for (;;) {                                   //1   
    5.             Node<E> t = tail;                        //2   
    6.             Node<E> s = t.getNext();                 //3   
    7.             if (t == tail) {                         //4   
    8.                 if (s == null) {                     //5   
    9.                     if (t.casNext(s, n)) {           //6   
    10.                         casTail(t, n);               //7   
    11.                         return true;                 //8   
    12.                     }   
    13.                 } else {   
    14.                     casTail(t, s);                   //9   
    15.                 }   
    16.             }   
    17.         }   
    18.     }  
    1. public boolean offer(E e) {  
    2.         if (e == null) throw new NullPointerException();  
    3.         Node<E> n = new Node<E>(e, null);  
    4.         for (;;) {                                   //1  
    5.             Node<E> t = tail;                        //2  
    6.             Node<E> s = t.getNext();                 //3  
    7.             if (t == tail) {                         //4  
    8.                 if (s == null) {                     //5  
    9.                     if (t.casNext(s, n)) {           //6  
    10.                         casTail(t, n);               //7  
    11.                         return true;                 //8  
    12.                     }  
    13.                 } else {  
    14.                     casTail(t, s);                   //9  
    15.                 }  
    16.             }  
    17.         }  
    18.     }  



    在有锁得情况下我们只要让获得锁得线程更新,其它线程等待即可解决并发更新的问题,但是在上述的单向链表结构中有更好的无锁解决方法。

    1.代码1 啊! 死循环,对,就是利用反复轮询的重复一段逻辑操作。
    2.代码2 代码3 先用两个临时变量指向CLQ的尾和尾的下一个节点。这样有什么好处?直接用tail和tail.getNext不行吗?我们说了。这是一个无锁得方法。可能有多个线程同时执行到代码3处,因为临时变量是每线程的而tail是公共的。这样成功执行到代码3的线程都有自己当时的临时CLQ队列结构引用。为后面的判断做好准备。
    3.开始判断 代码4 证明 在代码2 和代码4之间没有被其它线程修改过,因为有可能已经被修改了。那么这时进入新的轮询。
    4.代码5 在看代码5之前我们先要明确一个概念就是把一个Node放入一个CLQ队列有两步操作。第一步是tail的next指向新的节点。第二步是tail指向新的节点。代码5 先判断是不是有线程已经在完成加入一个节点的第一步,如果是就帮助它完成第二步,再次进入循环。如果没有线程已经完成第一步。那就自己来完成插入节点的第一步,当然就是调用casNext比较更新的原子操作。上文已经讲过。再来完成插入元素的第二步,以上逻辑由代码6、代码7完成。注意看代码8 恒为真? 为什么?自己调用casTail如果成功返回真毫无疑问。如果失败为什么也返回真?答案很简单,这是因为如果失败说明一定有其它线程进入了代码9 帮自己完成了插入一个节点的第二步操作。所以自己操作肯定是失败的。所以也返回真。

    从上面的代码分析可以看出打造一个无锁得并发容器处处都要十分小心。这也是CLQ的高明之处。

    我们再来看看删除一个元素的代码:

    Java代码 复制代码 收藏代码
    1. public E poll() {   
    2.         for (;;) {   
    3.             Node<E> h = head;                          //1   
    4.             Node<E> t = tail;                          //2   
    5.             Node<E> first = h.getNext();               //3   
    6.             if (h == head) {                           //4   
    7.                 if (h == t) {                          //5   
    8.                     if (first == null)                 //6   
    9.                         return null;                   //7   
    10.                     else  
    11.                         casTail(t, first);             //8   
    12.                 } else if (casHead(h, first)) {        //9   
    13.                     E item = first.getItem();          //10   
    14.                     if (item != null) {                //11   
    15.                         first.setItem(null);           //12   
    16.                         return item;                   //13   
    17.                     }   
    18.                     // else skip over deleted item, continue loop,   
    19.                 }   
    20.             }   
    21.         }   
    22.     }  
    1. public E poll() {  
    2.         for (;;) {  
    3.             Node<E> h = head;                          //1  
    4.             Node<E> t = tail;                          //2  
    5.             Node<E> first = h.getNext();               //3  
    6.             if (h == head) {                           //4  
    7.                 if (h == t) {                          //5  
    8.                     if (first == null)                 //6  
    9.                         return null;                   //7  
    10.                     else  
    11.                         casTail(t, first);             //8  
    12.                 } else if (casHead(h, first)) {        //9  
    13.                     E item = first.getItem();          //10  
    14.                     if (item != null) {                //11  
    15.                         first.setItem(null);           //12  
    16.                         return item;                   //13  
    17.                     }  
    18.                     // else skip over deleted item, continue loop,  
    19.                 }  
    20.             }  
    21.         }  
    22.     }  


    1.同样是轮询,当h!=head的时候继续循环。因为在代码1和代码4之间已经有其它线程删除了头元素。从而造成h != head.
    2.代码5 是否是空的CLQ。
    3.如果是空的CLQ判断头得下一节点是否是null.因为只有时空的才说明没有元素。否则有可能其它线程正在插入元素造成first!=null,这时就帮助其它线程完成为指针更新操作。再继续轮询。
    4.如果是非空的CLQ用casHead来原子更新头节点。因为删除一个CLQ的元素是从头开始删除的。如果失败说明有其它线程在删除元素。继续轮询。
    5.代码10 如果第一个元素的内容为空说明有线程已经执行到代码12了。所以又开始轮询。
    6.只有成功执行到代码13才正真是由当前线程完成了删除一个元素操作。CLQ的peek()操作和poll操作只差代码12的操作,即一个删除元素,一个不删除元素。

    在CLQ中迭代器的方法也很精妙:

    Java代码 复制代码 收藏代码
    1. private E advance() {   
    2.             lastRet = nextNode;   
    3.             E x = nextItem;   
    4.   
    5.             Node<E> p = (nextNode == null)? first() : nextNode.getNext();   
    6.             for (;;) {   
    7.                 if (p == null) {   
    8.                     nextNode = null;   
    9.                     nextItem = null;   
    10.                     return x;   
    11.                 }   
    12.                 E item = p.getItem();   
    13.                 if (item != null) {   
    14.                     nextNode = p;   
    15.                     nextItem = item;   
    16.                     return x;   
    17.                 } else // skip over nulls   
    18.                     p = p.getNext();   
    19.             }   
    20.         }  
    1. private E advance() {  
    2.             lastRet = nextNode;  
    3.             E x = nextItem;  
    4.   
    5.             Node<E> p = (nextNode == null)? first() : nextNode.getNext();  
    6.             for (;;) {  
    7.                 if (p == null) {  
    8.                     nextNode = null;  
    9.                     nextItem = null;  
    10.                     return x;  
    11.                 }  
    12.                 E item = p.getItem();  
    13.                 if (item != null) {  
    14.                     nextNode = p;  
    15.                     nextItem = item;  
    16.                     return x;  
    17.                 } else // skip over nulls  
    18.                     p = p.getNext();  
    19.             }  
    20.         }  



    由于CLQ单向链表的特殊性,元素的变化只可能头处删除,在尾处添加。所以使用CLQ的迭代器时元素可能比实际的要多。原因很简单,当你在迭代的时候元素可能已经删除,当然这是你迭代的线程是不可见的。而删除是可见的。


    ConcurrentLinkeQueue的其它操作大同小异。都是在不断的轮询中步步判断其它线程的影响,一步一步推进自己的操作逻辑。从而最终完成操作的。 

  • 相关阅读:
    IOS Charles(代理服务器软件,可以用来拦截网络请求)
    Javascript中addEventListener和attachEvent的区别
    MVC中实现Area几种方法
    Entity Framework Code First 中使用 Fluent API 笔记。
    自定义JsonResult解决 序列化类型 System.Data.Entity.DynamicProxies 的对象时检测到循环引用
    序列化类型 System.Data.Entity.DynamicProxies 的对象时检测到循环引用
    An entity object cannot be referenced by multiple instances of IEntityChangeTracker 的解决方案
    Code First :使用Entity. Framework编程(8) ----转发 收藏
    Code First :使用Entity. Framework编程(6) ----转发 收藏
    Code First :使用Entity. Framework编程(5) ----转发 收藏
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/6231721.html
Copyright © 2011-2022 走看看