Reputation: 11
What would happen if multiple threads are trying to access a queue implemented from LinkedList
as opposed to ConcurrentLinkedQueue
?
Assuming that each thread only uses add()
and poll()
and no other function calls, are those two operations atomic?
If they are atomic, then is there a benefit in using ConcurrentLinkedQueue
instead of a regular LinkedList
implementation?
Upvotes: 1
Views: 133
Reputation: 63955
It's undefined. A regular LinkedList
is not atomic / safe for a multi-threaded use.
You can wrap it in Collections.synchronizedList(LinkedList)
to gain atomic operations but it's still different. ConcurrentLinkedQueue
was specifically designed for use in a multi-threaded environment as "An unbounded thread-safe queue based on linked nodes". And you'll find several things it does differently if you read the documentation like
implementation employs an efficient non-blocking algorithm [...]
while a synchronized LinkedList
locks the entire list for every operation. But it also has downsides like
Beware that, unlike in most collections, the size method is NOT a constant-time operation.
It depends on your requirements but if you want a concurrent queue, it's pretty safe to assume that you shouldn't use a LinkedList
.
Upvotes: 1
Reputation: 2777
Those operations are not atomic. Looking at the source for LinkedList you can see add and poll call routines that are most definitely not safe for two threads to be executing on the same instance without synchronization.
Upvotes: 0