set

To err is human, but to really foul things up you need a computer. Paul Ehrlich

CopyOnWriteArraySet

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-24 11:06:51

0 Comments


Definition

A Set that uses an internal CopyOnWriteArrayList for all of its operations. It is useful when the list shares the data structure among several threads and have few writes and many reads.

Character

CopyOnWriteArraySet uses CopyOnWriteArrayList for all of its operations.
It is Thread safe.
The iteration does not support remove operations.
Support putidAbsent atomic operation, checks whether an equal element is already in the list and adds it only if it is not.

source Code

								
package com.careerdrill.collections.set;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

public class CopyOnWriteArraySetUse {
	
	private final CopyOnWriteArraySet< String > cwas = new CopyOnWriteArraySet< String >();
	
	public static void main(String... args){
		
		CopyOnWriteArraySetUse ob= new CopyOnWriteArraySetUse();
		System.out.println("Add 1 to the CopyOnWriteArraySet and pass to Thread");
		ob.cwas.add("1");
		
		new Thread(ob.new modifyThread(),"Thread1").start();
		new Thread(ob.new modifyThread(), "Thread2").start();
	}
	
	class modifyThread implements Runnable {
 
		@Override
		public void run() {
			Iterator< String > itr= cwas.iterator();
			String s=itr.next();
			cwas.removeAll(cwas);
			cwas.add(s+"2");
			itr= cwas.iterator();
			System.out.println("Update the value on CopyOnWriteArraySet "+ itr.next() +" from thread "+Thread.currentThread().getName());
		}
		
	}

}
						

Output

    					 
Add 1 to the CopyOnWriteArraySet and pass to Thread
Update the value on CopyOnWriteArraySet 12 from thread Thread1
Update the value on CopyOnWriteArraySet 122 from thread Thread2
    					 
					    

Comparison

CopyOnWriteArraySet ConcurrentSkipListSet
Uses CopyOnWriteArrayList for all of its operations. Implementation based on a ConcurrentSkipListMap.
Thread-safe. Execute concurrently by multiple threads.
Do not throw ConcurrentModificationException. Do not throw ConcurrentModificationException.
Traversal via iterators is fast and cannot encounter interference from other threads. Returns an iterator over the elements in this set in ascending order.

When to use

When set sizes generally stay small, read-only operations vastly outnumber mutative operations, you can choose CopyOnWriteArraySet. When you want to share the data structure among several threads and have few writes and many reads.

0 Comments



Please login to add comments.