简体   繁体   中英

Java (Android), thread safe FIFO without locking?

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.

  1. Yes, the methods add and poll of ConcurrentLinkedQueue are thread-safe (as all other methods).
  2. No, do not use ArrayList or LinkedList directly 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 a Queue )
  • LinkedBlockingQueue (is a BlockingQueue )
  • LinkedBlockingDeque (is a BlockingDeque )
  • ArrayBlockingQueue (is a BlockingQueue )

I assume, either Queue or BlockingQueue is the interface of your choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM