Saturday 19 July 2014

Fail Safe Iterator

Fail-safe iterator doesn't throw any Exception if Collection is modified structurally while one thread is Iterating over it because they work on clone of Collection instead of original collection.

import java.util.concurrent.*;
import java.util.*;

public class FailSafeEx implements Runnable{
    static CopyOnWriteArrayList<Integer> myList = new CopyOnWriteArrayList<> ();
    
    @Override
    public void run(){
        String name = Thread.currentThread().getName();
        if(name.equals("thread1"))
            iterateList();
        else
           updateList(); 
    }
    
    static void iterateList(){
        Iterator<Integer> myIter;
        myIter = myList.iterator();
        
        while(myIter.hasNext()){
            myIter.next();
            try{
                Thread.sleep(100);
            }
            catch(InterruptedException e){
                
            }
        }
    }
    
    static void updateList(){
        for(int i=20; i<30; i++){
            myList.add(i);
            try{
                Thread.sleep(100);
            }
            catch(InterruptedException e){
                
            }
        }
    }
    
    public static void main(String args[])throws Exception{
        
        for(int i=0; i<10; i++)
            myList.add(i);
        
        Thread t1 = new Thread(new FailSafeEx());
        Thread t2 = new Thread(new FailSafeEx());
        
        t1.setName("thread1");
        t2.setName("thread2");
                
        t1.start();
        t2.start();
    }
}

As you observe the above program, while thread 't1' iterating over the list, another thread add elements. But it won't throw any exception,since it is fail safe.




                                                             Home

No comments:

Post a Comment