简体   繁体   English

Java(Android),没有锁定的线程安全FIFO?

[英]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. 一个从池中取出对象,然后将它们放入fifo,另一个从中读取对象(一次多个),进行计算,从列表中删除它们,然后将它们放回池中。
With ConcurrentLinkedQueue that pattern should be thread safe without additional locks. 使用ConcurrentLinkedQueue时,该模式应该是线程安全的,没有其他锁定。 Each object is only written once, read once and removed once. 每个对象仅写入一次,读取一次并删除一次。 Add() and Poll() are safe in CLQ. Add()和Poll()在CLQ中是安全的。
a) Is this correct? a)这是正确的吗?
b) Which other Containers support this specific pattern? b)还有哪些其他容器支持此特定模式? 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. 我记得关于LinkedList甚至ArrayList的事情是安全的,因为“ getSize()”或“ head = ...”具有一些原子效应,但我不确定并且找不到它。

  1. Yes, the methods add and poll of ConcurrentLinkedQueue are thread-safe (as all other methods). 是的, ConcurrentLinkedQueue addpoll方法是线程安全的(与所有其他方法一样)。
  2. No, do not use ArrayList or LinkedList directly in a concurrent environment. 不, 使用ArrayListLinkedList在并发环境直接。 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. 如果多个线程同时访问ArrayList实例,并且至少有一个线程在结构上修改列表,则必须在外部进行同步。

If you are not satisfied with ConcurrentLinkedQueue , have a look at all those container implementations in package java.util.concurrent : 如果您对ConcurrentLinkedQueue不满意,请查看包java.util.concurrent所有那些容器实现:

  • ConcurrentLinkedDeque (is a Queue ) ConcurrentLinkedDeque (是一个Queue
  • LinkedBlockingQueue (is a BlockingQueue ) LinkedBlockingQueue (是BlockingQueue
  • LinkedBlockingDeque (is a BlockingDeque ) LinkedBlockingDeque (是BlockingDeque
  • ArrayBlockingQueue (is a BlockingQueue ) ArrayBlockingQueue (是一个BlockingQueue

I assume, either Queue or BlockingQueue is the interface of your choice. 我假设QueueBlockingQueue是您选择的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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