java 并发 LinkedList 与 ConcurrentLinkedQueue

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38356636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:20:23  来源:igfitidea点击:

Concurrent LinkedList vs ConcurrentLinkedQueue

javamultithreadingconcurrency

提问by serah

I need a concurrent list that is thread safe and at the same time is best for iteration and should return exact size. I want to to store auction bids for an item. So I want to be able to

我需要一个线程安全的并发列表,同时最适合迭代并且应该返回精确的大小。我想存储一个项目的拍卖出价。所以我希望能够

  1. retrieve the exact number of bids for an item
  2. add a bid to a item
  3. retrieve all the bids for a given item.
  4. Remove a bid for a item
  1. 检索项目的确切出价数量
  2. 为项目添加出价
  3. 检索给定项目的所有出价。
  4. 删除对项目的出价

I am planning to have it in a ConcurrentHashMap<Item, LinkedList<ItemBid>>-- LinkedList is not thread safe but returns exact size ConcurrentHashMap<Item, ConcurrentLinkedQueue<ItemBid>>- concurrentlinked queue is thread safe but does not guarantee to return exact size

我打算把它放在一个 ConcurrentHashMap<Item, LinkedList<ItemBid>>-- LinkedList 不是线程安全的,但返回精确的大小 ConcurrentHashMap<Item, ConcurrentLinkedQueue<ItemBid>>- concurrentlinked 队列是线程安全的,但不保证返回精确的大小

Is there any other better collection that will address the above 4 points and is thread safe.

有没有其他更好的集合可以解决上述 4 点并且是线程安全的。

回答by Mena

Well arguably in a thread-safe collection ormap you cannot guarantee the "consistency" of the size, meaning that the "happen-before" relationship between read and write operations will not benefit your desired use case, where a read operation on the size should return a value reflecting the exact state from the last write operation (N.B.: improved based on comments - see below).

可以说,在线程安全的集合映射中,您无法保证大小的“一致性”,这意味着读取和写入操作之间的“先发生”关系不会有利于您所需的用例,其中读取操作对大小应该返回一个反映上次写入操作的确切状态的值(注意:根据评论改进 - 见下文)。

What you cando if performance is not an issue is to use the following idiom - either:

如果性能不是问题,您可以做的是使用以下习语 - 要么:

  • Collections.synchronizedMap(new HashMap<YourKeyType, YourValueType>());
  • Collections.synchronizedList(new ArrayList<YourType>());
  • Collections.synchronizedMap(new HashMap<YourKeyType, YourValueType>());
  • Collections.synchronizedList(new ArrayList<YourType>());

You'll then also need to explicitly synchronize over those objects.

然后,您还需要显式同步这些对象。

This will ensure the order of operations is consistent at the cost of blocking, and you should get the last "right" size at all times.

这将确保以阻塞为代价的操作顺序是一致的,并且您应该始终获得最后一个“正确”的大小。

回答by John Vint

You can use LinkedBlockingQueue. It is blocking (as apposed to the CLQ) but size is maintained and not scanned like the CLQ.

您可以使用LinkedBlockingQueue。它是阻塞的(与 CLQ 相关)但大小保持不变,不像 CLQ 那样被扫描。