ConcurrentLinkedDeque vs LinkedBlockingDeque

后端 未结 4 1619
故里飘歌
故里飘歌 2021-02-07 05:53

I need to have a thread-safe LIFO structure and found that I can use thread-safe implementations of Deque for this. Java 7 has introduced ConcurrentLinkedDeque and

4条回答
  •  深忆病人
    2021-02-07 06:23

    Two things:

    1: If I were to use only the non-blocking methods in LinkedBlockingDeque such as addFirst() and removeFirst() does it have any difference to ConcurrentLinkedDeque?

    These methods do have difference in terms of concurrent locking behavior, in LinkedBlockingDeque:

    public E removeFirst() {
            E x = pollFirst();
            ..
        }
     public E pollFirst() {
            lock.lock(); //Common lock for while list
            try {
                return unlinkFirst();
            } finally {
                lock.unlock();
            }
        }
    

    Similarly for addFirst method. In ConcurrentLinkedDeque this locking behavior for both the method is different and is more efficient as it doesn't lock the whole list but a subset of it, checking source for ConcurrentLinkedDeque will give you more clarity on this.

    2: From javadoc of ConcurrentLinkedDeque:

    Beware that, unlike in most collections, the size method is NOT a constant-time operation.

    ..

    Additionally, the bulk operations addAll, removeAll, retainAll, containsAll, equals, and toArray are not guaranteed to be performed atomically.

    Above is not true for LinkedBlockingDeque

提交回复
热议问题