How to sort CopyOnWriteArrayList

前端 未结 5 1654
名媛妹妹
名媛妹妹 2021-02-06 08:46

I want to sort CopyOnWriteArrayList. But when I tried to run the following code

It is throwing unsorted operation exception.



        
5条回答
  •  佛祖请我去吃肉
    2021-02-06 09:18

    Evgeniy's solution points in the right way, but list.set(i, (String) a[i]) has to gain the lock on list for each element in the list. If there is a concurrent thread which writes into list this will slow down the loop dramatically.

    To minimize blocking it's better to reduce the number of statements which alter list:

        CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
    
        // ... fill list with values ...
    
        ArrayList temp = new ArrayList<>();
        temp.addAll(list);                           
        Collections.sort(temp);
    
        list.clear();            // 1st time list is locked
        list.addAll(temp);       // 2nd time list is locked
    

    The downside is that if a concurrent thread reads list between clear() and addAll(temp) it will see an empty list wheras with Evgeniy's solution it may see a partially sorted list.

提交回复
热议问题