ConcurrentLinkedQueue
是一个无界的,线程安全的队列,遵循FIFO
先进先出规则。
当使用多线程访问需求时,该队列是一个不错的选择,和其他并发集合类似,它也不接受Null
元素否则将抛出NullPointerException
。
//其offer方法的首行调用该方法检查空值。
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
}
该队列仅有两个构造器:
public ConcurrentLinkedQueue() {
head = tail = new Node<E>(null);
}
调用构造器时将队头和队尾都设置为节点Null
。
public ConcurrentLinkedQueue(Collection<? extends E> c) {
Node<E> h = null, t = null;
for (E e : c) {
checkNotNull(e); //判空
Node<E> newNode = new Node<E>(e);
if (h == null)
h = t = newNode;
else {
t.lazySetNext(newNode);
t = newNode;
}
}
//如果入参collection.size() = 0即未插入元素,则调用w
if (h == null)
h = t = new Node<E>(null);
head = h;
tail = t;
}
该队列是线程安全的。
Queue<User> queue = new ConcurrentLinkedQueue<>();
CountDownLatch countDownLatch = new CountDownLatch(3);
new Thread(() -> {
for (int i = 0; i < 1000; i++) {
queue.add(new User(new Random().nextInt(100)));
System.out.println("thread name: " + Thread.currentThread().getName());
}
countDownLatch.countDown();
},"A").start();
new Thread(() -> {
for (int i = 0; i < 1000; i++) {
queue.add(new User(new Random().nextInt(100)));
System.out.println("thread name: " + Thread.currentThread().getName());
}
countDownLatch.countDown();
},"B").start();
new Thread(() -> {
for (int i = 0; i < 1000; i++) {
queue.add(new User(new Random().nextInt(100)));
System.out.println("thread name: " + Thread.currentThread().getName());
}
countDownLatch.countDown();
},"C").start();
try {
countDownLatch.await();
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("queue.size() = " + queue.size());
int i = 0;
while (!queue.isEmpty()) {
queue.poll();
i++;
}
System.out.println("i = " + i);
该队列的迭代器是弱一致性的,反映的总是队列某一瞬间的状态。
弱一致性测试:
Queue<User> queue = new ConcurrentLinkedQueue<>();
//开启线程插入元素
new Thread(() -> {
while (true) {
queue.add(new User(new Random().nextInt(100)));
}
},"A").start();
//等待线程插入一些
try {
TimeUnit.SECONDS.sleep(2);
}catch (InterruptedException e) {
e.printStackTrace();
}
//获取迭代器
Iterator<User> iterator = queue.iterator();
int size = 0;
while (iterator.hasNext()) {
iterator.next();
size++;
}
System.out.println("size = " + size);
//睡眠两秒钟,重新遍历相同迭代器,查看是否size增加
try {
TimeUnit.SECONDS.sleep(2);
}catch (InterruptedException e) {
e.printStackTrace();
}
while (iterator.hasNext()) {
iterator.next();
size++;
}
System.out.println("size = " + size);
//获取一个新的迭代器,重新查看size
iterator = queue.iterator();
while (iterator.hasNext()) {
iterator.next();
size++;
}
System.out.println("size = " + size);
运行结果:
这里我的想法是:开启一个线程不断向队列中添加元素,每隔一段时间查看迭代器遍历内个数。
这里需要注意的是,在获取迭代器后插入元素并不会引发ConcurrentModificationException
,相反,ConcurrentLinkedQueue
是允许在获取迭代器后插入元素的。
从运行结果不难看出,迭代器永远反应的是队列在迭代器被获取时刻的状态,直到获取了新的迭代器。
这里为什么不用队列的size()
方法来获取元素个数呢,可以看看源码中的解释:
/**
* Returns the number of elements in this queue. If this queue
* contains more than {@code Integer.MAX_VALUE} elements, returns
* {@code Integer.MAX_VALUE}.
*
* <p>Beware that, unlike in most collections, this method is
* <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these queues, determining the current
* number of elements requires an O(n) traversal.
* Additionally, if elements are added or removed during execution
* of this method, the returned result may be inaccurate. Thus,
* this method is typically not very useful in concurrent
* applications.
*
* @return the number of elements in this queue
*/
首先,这个方法和其他collection
集合不同,它的size
是需要计算的,时间复杂度为O(n)
。
如果在计算过程中队列被改变,即插入或取出了元素,则这个方法返回的长度可能是不准确的。
因此,这个方法并不是那么有用。
但这个队列也具备最终一致性,它会随着时间越来越趋向于一致。