Java并发包探秘 (一) ConcurrentLinkedQueue
本文是Java并发包探秘的第一篇,旨在介绍一下Java并发容器中用的一些思路和技巧,帮助大家更好的理解Java并发容器,让我们更好的使用并发容器打造更高效的程序。本人能力有限,错误难免。希望及时指出。
Java并发包中有很多精心设计的高并发容器。有ConcurrentHashMap、ConcurrentSkipListMap 、ConcurrentLinkedQueue等。ConcurrentLinkedQueue就是其中设计最为优雅的高并发容器。它被设计成了无锁的、无界的、非阻塞式的单向链表结构。现在就让我们来一步一步揭开他们神秘的面纱。
正文开始:
一说到链表结构,我们首先就会想到的就是组成链表结构的原件,那就是节点。或者有的人称之为元素。ConcurrentLinkedQueue(为了叙述方便后面用CLQ指代)中称之为Node.
我们先来看看CLQ中Node的结构:
private E advance() { lastRet = nextNode; E x = nextItem; Node<E> p = (nextNode == null)? first() : nextNode.getNext(); for (;;) { if (p == null) { nextNode = null; nextItem = null; return x; } E item = p.getItem(); if (item != null) { nextNode = p; nextItem = item; return x; } else // skip over nulls p = p.getNext(); } }