CopyOnWriteArrayList implements an efficient List::replaceAll so you could do 
something like:

====
public static void main(String[] args) {
        List<String> cowl = new CopyOnWriteArrayList<>(new 
String[]{"1","2","3"});
        List<String> copy = Arrays.asList(cowl.toArray(new String[0]));
        Collections.shuffle(copy);
        Iterator<String> it = copy.iterator();  
        try {
                cowl.replaceAll(e -> it.next());
        } catch (NoSuchElementException nsee) {
                throw new ConcurrentModificationException();
        }
                
        if (it.hasNext()) {
                throw new ConcurrentModificationException();
        }

        System.out.println(cowl);
}
====

Some of the non-random access branches in Collections.java could be updated to 
use List::replaceAll over ListIterator next/set.  Once Collections.java was 
using List::replaceAll you could then just wrap CopyOnWriteArrayList in a 
non-random access list.

Jason

________________________________________
From: core-libs-dev <core-libs-dev-r...@openjdk.org> on behalf of Zelva Lia 
<jolyj...@gmail.com>
Sent: Friday, August 19, 2022 5:49 AM
To: core-libs-dev@openjdk.org
Subject: CopyOnWriteArrayList Collection.shuffle

Hello, when shuffling the CopyOnWrite list with the standard 
Collections.shuffle method, performance anomalies occur, due to the fact that 
it calls the set method, which copies the array each time, a possible solution 
(crutch) is a random comparator for sorting, so sorting in COW is redefined to 
its own sub - blocking implementation

Another problem with Collections.shuffle is that it's not exactly thread safe 
because it calls the size() method; and then iterates from it, also COW does 
not support modification inside the iterator (works on snapshots)


COWCollectionsShuffle      0,008 ops/ms
COWListRandomSort         1,089 ops/ms
syncListCollectionsShuffle  0,950 ops/ms

Reply via email to