简体   繁体   English

多个线程同时写入集合

[英]Multiple threads writing in a collection concurrently

I am having a scenario, in which lot of threads needs to share a collections and the threads keep on writing in the collection, comparatively writes are many and reads are very less, I am not sure ArrayBlockQueue is a correct collection to be used. 我有一个场景,其中许多线程需要共享集合并且线程继续在集合中写入,相对写入很多并且读取非常少,我不确定ArrayBlockQueue是否是要使用的正确集合。 Should I implement my own collection or do I get anything out of the Box in Java? 我应该实现自己的集合还是在Java中获得任何开箱即用的东西?

Please help. 请帮忙。

I suggest you read the code for ArrayBlockingQueue and Disruptor first. 我建议你首先阅读ArrayBlockingQueueDisruptor的代码。 If you think you can do it much better, you might write your own, but it is highly likely that writing your own won't be as performant, or well tested. 如果您认为自己可以做得更好,那么您可以自己编写,但编写自己的文章很可能不会具有高效性或经过充分测试。

Generally systems that adhere to the "single writer principle" can obtain better performance. 通常,遵循“单一写入原则”的系统可以获得更好的性能。 The concurrent collections do support multiple writers, but if instead you let each thread write to their own collections and the reader goes over each of them you'll likely get less contention and better throughput. 并发集合确实支持多个编写器,但是如果你让每个线程写入他们自己的集合并且读者遍历每个集合,你可能会获得更少的争用和更好的吞吐量。

It depends on what do you look for "collection". 这取决于你对“收藏”的看法。

ArrayBlockingQueue as its name suggested is a Blocking Queue. 建议使用ArrayBlockingQueue作为阻塞队列。 If you simply want a collection to store bunch of data and read it, without using those blocking put/take operations, ArrayBlockingQueue is probably nothing different from a synchronized ArrayList. 如果您只是想要一个集合来存储大量数据并读取它,而不使用那些阻塞put / take操作,ArrayBlockingQueue可能与同步的ArrayList没什么不同。 Think again what you are using the collection for. 再想想你使用该系列的内容。

Java provided some lock-free collections, like ConcurrentLinkedQueue. Java提供了一些无锁的集合,比如ConcurrentLinkedQueue。 If you are not looking for a BlockingQueue, these collections may offer you better performance. 如果您不是在寻找BlockingQueue,这些系列可能会为您提供更好的性能。

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

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