Java Synchronized list

后端 未结 7 2136
一整个雨季
一整个雨季 2020-12-01 06:13

I have a pre-populated array list. And I have multiple threads which will remove elements from the array list. Each thread calls the remove method below and removes one item

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 06:41

    That should be fine as long as you don't require the "remove" method to be atomic.

    In other words, if the "do something" checks that the item appears more than once in the list for example, it is possible that the result of that check will be wrong by the time you reach the next line.

    Also, make sure you synchronize on the list when iterating:

    synchronized(list) {
        for (Object o : list) {}
    }
    

    As mentioned by Peter Lawrey, CopyOnWriteArrayList can make your life easier and can provide better performance in a highly concurrent environment.

提交回复
热议问题