简体   繁体   English

用于快速并发插入的最佳Java数据结构

[英]Best Java Data Structure for Fast, Concurrent Insertions

My use case is as follows: I have 10 threads simultaneously writing to one data structure. 我的用例如下:我有10个线程同时写入一个数据结构。 The order of the elements in the data structure does not matter. 数据结构中元素的顺序无关紧要。 All the elements are unique. 所有元素都是独一无二的。 I will only be doing a read from this data structure only once at the very end. 我只会在最后一次从这个数据结构中读取一次。

What would be the fastest native Java data structure to suit this purpose? 什么是最适合此目的的本机Java数据结构? From my reading, it seems Collections.synchronizedList might be the go to option? 从我的阅读,似乎Collections.synchronizedList可能是转到选项?

I have 10 threads simultaneously writing to one data structure. 我有10个线程同时写入一个数据结构。

I think it would be best to use a separate data structure per thread. 我认为最好每个线程使用一个单独的数据结构。 That way no synchronisation is needed between the threads, and it would be much more CPU cache friendly too. 这样,线程之间不需要同步,而且CPU缓存也更友好。

At the end they could be joined. 最后他们可以加入。

As for the underlying structure: if the elements are fixed size, an array/verctor would be best. 至于底层结构:如果元素是固定大小,则数组/检查器最好。 Joining them would only take a copy of the block of memory they occupy, depending on the implementation - but lists would always be slower. 加入它们只会获取它们占用的内存块的副本 ,具体取决于实现 - 但列表总是会更慢。

There is no need for you to synchronize on a list as each of the thread can work on their local copy and at the end can join results from all the threads into one final list. 您无需在列表上进行同步,因为每个线程都可以在其本地副本上工作,最后可以将所有线程的结果连接到一个最终列表中。

If am going to use JDK7 and above then I would use fork and join for the same where i would create simple List in each forked task and finally join it in the main list at the end in the join phase. 如果我将使用JDK7及更高版本,那么我将使用fork和join,我将在每个分叉任务中创建简单List ,最后在连接阶段结束时将其加入主列表中。

If am on JDK6 then i could use a CountDownLatch with count as 10. Each and every thread after writing to their individual list (passed to the thread from main controller thread) counts down the latch and in the main controller, once all threads are done, i would combine all the result into one. 如果我在JDK6上,那么我可以使用CountDownLatch ,其数量为10.在写入各自的列表(从主控制器线程传递到线程)后,每个线程都会对锁存器和主控制器进行倒计时,一旦完成所有线程,我会把所有的结果合二为一。

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

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