Joker
Joker

Reputation: 11156

CopyOnWriteArraySet is too slow

When I ran the following program, it took around 7 to 8 minutes to execute. I am really not sure where I am mistaken as this program is taking so much time to execute.

public class Test {
            public static void main(String[] args) {
            final Integer[] a= new Integer[1000000];
            for (int i=0; i < a.length; i++) {
                a[i] = i;
            }
            final List<Integer> source = Arrays.asList(a);
            final Set<Integer> set = new CopyOnWriteArraySet<Integer>(source);
        }
    }

Can some one help me understand, why this program is too slow.

My machine is Core I7 with 4GB RAM

Upvotes: 1

Views: 443

Answers (1)

davidxxx
davidxxx

Reputation: 131456

I have tested and indeed with a List of 1 000 000 elements provided to the constructor, it takes a good time (7 minutes).

It is a referenced issue on Open JDK the 2013-01-09 :
JDK-8005953 - CopyOnWriteArraySet copy constructor is unusable for large collections

The problem would cause by the CopyOnWriteArrayList#addAllAbsent() method invoked by the CopyOnWriteArraySet constructor.

Extract of the issue :

CopyOnWriteArraySet's copy constructor is too slow for large collections. It takes over 10 minutes on a developer laptop with just 1 million entries in the collection to be copied...

As resolution status, you can read : Won't Fix.
And you can read as last message :

addAllAbsent can be made faster for larger input, but it would impact the performance for small sizes. And it's documented that CopyOnWriteXXX classes are better suited for collections of small sizes.

The CopyOnWriteArraySet javadoc specifies indeed this point :

It is best suited for applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to prevent interference among threads during traversal.

Upvotes: 7

Related Questions