views:

309

answers:

3

Hi,

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.

+1  A: 

No LinkedList is not thread safe. Use LinkedBlockingDeque instead

nanda
+4  A: 

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

Try ConcurrentLinkedQueue or LinkedBlockingDeque instead if it fits your needs

nos
+1  A: 

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.
}
Benoit Courtine
I generally tend to prefer existing classes over implementing my own. So I'll go with one of the other two suggestions. But thank you anyway.
André Hoffmann