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 Java 6 has LinkedBlockingDeque.
If I were to use only the non-blocking methods in LinkedBlockingDeque such as addFirst() and removeFirst() does it have any difference to ConcurrentLinkedDeque?
i.e. If you disregard the blocking aspect, is there any other difference between ConcurrentLinkedDeque and LinkedBlockingDeque, apart from LinkedBlockingDeque being bounded?
解决方案
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