I have a producer-consumer situation with exactly two threads. One takes objects from a pool and puts them in a fifo, the other one reads the objects (multiples at a time), does calculations, removes them from the list and puts them back in the pool.
With ConcurrentLinkedQueue that pattern should be thread safe without additional locks. Each object is only written once, read once and removed once. Add() and Poll() are safe in CLQ.
a) Is this correct?
b) Which other Containers support this specific pattern? I remember things about LinkedList or even ArrayList being safe because of some atomic effects with "getSize()" or "head=..." but i am not sure and could not find it.
0
votes
The most important thing to know about concurrency bugs is that a buggy program may work some of the time, and it may even work all of the time in some environments. You can't count on testing. So the best way to stay out of trouble is to read the documentation and follow the rules. The javadoc for the standard ArrayList and LinkedList classes explicitly says that they are not thread safe.
- Solomon Slow
The comment about threading/concurrency is correct. IMHO, if the fifo push/pop methods are atomic, then it should be OK. You need to make sure though that you don't end up with pool-related concurrency issues either (i.e. the object is controlled by a single entity/thread at any point).
- Laur Ivan
1 Answers
2
votes
- Yes, the methods
addandpollofConcurrentLinkedQueueare thread-safe (as all other methods). - No, do not use
ArrayListorLinkedListdirectly in a concurrent environment. These classes are not thread-safe by definition:
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
If you are not satisfied with ConcurrentLinkedQueue, have a look at all those container implementations in package java.util.concurrent:
ConcurrentLinkedDeque(is aQueue)LinkedBlockingQueue(is aBlockingQueue)LinkedBlockingDeque(is aBlockingDeque)ArrayBlockingQueue(is aBlockingQueue)
I assume, either Queue or BlockingQueue is the interface of your choice.