Java concurrency - improving a copy-on-read collection

后端 未结 5 882
梦毁少年i
梦毁少年i 2021-01-07 06:15

I have a multithreaded application, where a shared list has write-often, read-occasionally behaviour.

Specifically, many threads will dump data into the list, and th

5条回答
  •  感情败类
    2021-01-07 06:43

    Yes, there is a way. It is similar to the way ConcurrentHashMap made, if you know.

    You should make your own data structure not from one list for all writing threads, but use several independent lists. Each of such lists should be guarded by it's own lock. .add() method should choose list for append current item based on Thread.currentThread.id (for example, just id % listsCount). This will gives you good concurrency properties for .add() -- at best, listsCount threads will be able to write without contention.

    On makeSnapshot() you should just iterate over all lists, and for each list you grab it's lock and copy content.

    This is just an idea -- there are many places to improve it.

提交回复
热议问题