Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is LinkedList thread-safe when I'm accessing it with offer and poll exclusively?

Tags:

I have a linked list samples:

protected LinkedList<RawDataset> samples = new LinkedList<RawDataset>(); 

I'm appending elements to the list in thread 1 like this:

this.samples.offer(data); 

And I'm retrieving elements from it in a second thread like so:

public RawDataset retrieveSample() {     return this.samples.poll(); } 

Would this be considered as thread-safe? Even though thread 1 and 2 are both modifying the list they only do so on either the head or the tail of the list exclusively, right?

If it isn't can anyone point me to a class in the Java API that comes with poll/offer and is sure to be thread-safe?

Thank you in advance.

BTW: Collections.synchronizedList(new LinkedList()) won't give me access to offer/poll.

like image 235
André Hoffmann Avatar asked Jul 29 '10 11:07

André Hoffmann


People also ask

Is a LinkedList thread-safe?

Not Thread-safe: LinkedList is not suitable for concurrent access.

Which option is thread-safe?

1) Immutable objects are by default thread-safe because their state can not be modified once created. Since String is immutable in Java, it's inherently thread-safe. 2) Read-only or final variables in Java are also thread-safe in Java. 3) Locking is one way of achieving thread-safety in Java.

Why are lists not thread-safe?

In fact, by default, classes are not thread-safe. Being thread-safe would mean that any operation modifying the list would need to be interlocked against simultaneous access. This would be necessary even for those lists that will only ever be used by a single thread. That would be very inefficient.

Which collections are thread-safe in Java?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.


2 Answers

LinkedList is not thread safe. You'd have to do the locking yourself.

Try ConcurrentLinkedQueue or LinkedBlockingDeque instead if it fits your needs, they are thread safe but slightly different behavior than LinkedList.

like image 107
nos Avatar answered Oct 24 '22 19:10

nos


if you have a JDK, you can look at the source code of "Collections.synchronizedList()". It is simple, so you can create a copy of this method specialized to get both LinkedList and synchronization functionnalities.

public class SynchronizedLinkedList<T> implements List<T> {      private LinkedList<T> list;      private Object lock;      public void add(T object) {         synchronized(lock) {             list.add(object);         }     }      // etc. } 
like image 39
Benoit Courtine Avatar answered Oct 24 '22 20:10

Benoit Courtine