简体   繁体   中英

Best Java Data Structure for Fast, Concurrent Insertions

My use case is as follows: I have 10 threads simultaneously writing to one data structure. 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? From my reading, it seems Collections.synchronizedList might be the go to option?

I have 10 threads simultaneously writing to one data structure.

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.

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.

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.

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