- Thread safe version of ArrayList
- For every write operation a separate copy of the list if created and it is updated to achieve thread safety.(A copy is created so that the threads which are currently accessing the list need not stop). Later the original and copy of list will be synced by the JVM
- Other than above points CopyOnWriteArrayList is similar to ArrayList
Note : If 1000 update are needed to be done on array list then 1000 copies of arraylist will be created in memory which is a big performance overhead. Hence CopyOnWriteArrayList is recommended only when less number of write operation is to be performed. If more number of write is required then rather make the ArrayList as volatile and don’t iterate the list while that is happening.
Similar Points : (Between ArrayList and CopyOnWriteArrayList)
- Insertion order is preserved.
- Heterogeneous Objects are allowed
- Null insertion is allowed
- Implements Serializable, Clonable and RandomAccess
Unique Points : Between ArrayList and CopyOnWriteArrayList
- No Concurrent Modification Exception when modified while Iterating CopyOnWriteArrayList
- ArrayList Iterator can perform remove() operation on Iterator Object but when remove() method is called on CopyOfWriteArrayList then UnsupportedOperationException is thrown at runtime.
Constructors and Methods
CopyOnWriteArrayList l1 = new CopyOnWriteArrayList(); CopyOnWriteArrayList l2 = new CopyOnWriteArrayList(Collection c); CopyOnWriteArrayList l3 = new CopyOnWriteArrayList(Object[] a);
Two new methods of CopyOnWriteArrayList
- boolean addIfAbsent(Object o);
2. int addAllAbsent(Collection c)
Example :
Example 2:
package com.demo; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; public class COWALDemo extends Thread{ static List<String> cowAL= new CopyOnWriteArrayList<>(); // static List<String> cowAL= new ArrayList<>(); public void run() { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } cowAL.add("K"); } public static void main(String[] args) throws InterruptedException { cowAL.add("A"); cowAL.add("B"); cowAL.add("C"); cowAL.add("D"); cowAL.add("E"); cowAL.add("F"); Iterator<String> itr = cowAL.iterator(); COWALDemo temp = new COWALDemo(); temp.start(); while(itr.hasNext()) { System.out.println(itr.next()); TimeUnit.SECONDS.sleep(1); } } }
Reference :