Searching...
Thursday, 9 May 2013

Thread safe Arraylist Example (CopyOnWriteArrayList Example)

11:09

What is CopyOnWriteArrayList ?

 A thread-safe variant of java.util.ArrayList in which all mutative operations (add,set,and so on) are implemented by making a fresh copy of the underlying array.

Example

package com.collections;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample {
    public static void main(String[] args) {
        ArrayList al = new ArrayList();
        al.add("sunday");
        al.add("monday");
        al.add("tuesday");
        Iterator<String> alIterator = al.iterator();
        while (alIterator.hasNext()) {
            String value = alIterator.next();
                al.add("wednesday");
        }
        System.out.println(al);
        CopyOnWriteArrayList coal = new CopyOnWriteArrayList();
        coal.add("sunday");
        coal.add("monday");
        coal.add("tuesday");
        Iterator<String> coalIterator = coal.iterator();
        while (coalIterator.hasNext()) {
            String value = coalIterator.next();
                coal.add("wednesday");
        }
        System.out.println(coal);
    }
}

Output

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at com.collections.CopyOnWriteArrayListExample.main(CopyOnWriteArrayListExample.java:17)

In this example while adding element in to ArrayList throwing above exception, to overcome this we can make use of CopyOnWriteArrayList.

Please comment below line and run the program

    al.add("wednesday");

Output after commenting

[sunday, monday, tuesday]
[sunday, monday, tuesday, wednesday, wednesday, wednesday]

0 comments: