ConcurrentLinkedQueue

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);

image-20210915104047975

该队列的迭代器是弱一致性的,反映的总是队列某一瞬间的状态。

弱一致性测试:

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);

运行结果:

image-20210915110625222

这里我的想法是:开启一个线程不断向队列中添加元素,每隔一段时间查看迭代器遍历内个数。

这里需要注意的是,在获取迭代器后插入元素并不会引发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)

如果在计算过程中队列被改变,即插入或取出了元素,则这个方法返回的长度可能是不准确的。

因此,这个方法并不是那么有用。

但这个队列也具备最终一致性,它会随着时间越来越趋向于一致。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值