List

The key to performance is elegance, not battalions of special cases. Jon Bentley and Doug McIlroy

CopyOnWriteArrayList

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 19:58:25

0 Comments


Definition

Thread safe variant of ArrayList in which all the operations are implemented by making the new copy of the array. CopyOnWriteArrayList is very expensive because it involves costly due to Array copy and itís very efficient if you have a List where Iteration outnumbers mutation and do not throw concurrent modification Exception.

Character

CopyOnWriteArrayList creates a copy of underlying ArrayList with every mutation operation.
It's very efficient if you have a List where mostly need to iterate and don't modify it too often.
It doesn't throw ConcurrentModificationException.
CopyOnWriteArrayList uses ReentrantLock in addition to copying the underlying collection.
It provides snapshot-style fail-safe iterator.

source Code

								
package com.careerdrill.collections.list;

import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListUse {

	public static void main(String[] args) {
		Integer []array = {1, 2, 3, 4, 5};
		
		System.out.println("List of items in the array: " + Arrays.toString(array));
        final CopyOnWriteArrayList< Integer > numbers = new CopyOnWriteArrayList< >(
                Arrays.asList(array));
 
        System.out.println("Create new thread to concurrently modify the list");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                	System.out.println("Sleep 500 ms to print the value in the list");
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                numbers.add(10);
                System.out.println("numbers:" + numbers);
            }
        }).start();
 
        for (int i : numbers) {
            System.out.println(i);

            try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }

	}

}
						

Output

    					 
List of items in the array: [1, 2, 3, 4, 5]
Create new thread to concurrently modify the list
Sleep 500 ms to print the value in the list
1
2
3
Numbers:[1, 2, 3, 4, 5, 10]
4
5
    					 
					    

Comparison

CopyOnWriteArrayList ArrayList
CopyOnWriteArrayList is a thread-safe collection ArrayList is NOT thread-safe and cannot be used in multi-threaded
create a separate copy of List for each write operation Do not copy of List for each write operation
CopyOnWriteArrayList does not support remove operation Support remove operation
CopyOnWriteArrayList is fail-safe and do not throw ConcurrentModificationException throw ConcurrentModificationException
Reads do not block, and effectively pay only the cost of a volatile read Do not support in multithreaded environment

When to use

You can choose the CopyOnWriteArrayList when the application read most of the time and write very few times and the array is small.

0 Comments



Please login to add comments.