Need : (3 Major Reasons)
- Collections like ArrayList and LinkedList can be accessed by multiple Threads but they create DataInconsistency problems. (Not Thread Safe)
- Collections like Vector, Hashtable and Stack are Thread safe because their methods are synchronized. Hence multiple threads can’t work on them concurrently hence we can’t improve the performance of a Java job even when we use multithreading. Also (synchronizedList(), synchronizedSet(), synchronizedMap())
- For these ThreadSafe collections even for read operation, only one thread is allowed to execute at a time.
- If one thread is trying to iterate a collection at the same time another thread is trying to modify the collection immediately we will get ConucrrentModificationException
Example of ConcurrentModificationException
Simple Example :
public class ConcurrentModificationExceptionDemo { static List<Integer> tempList= new ArrayList<>(); public static void main(String[] args) { tempList.add(1); tempList.add(2); tempList.add(3); Iterator<Integer> itr = tempList.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); tempList.add(4); } } }
Complex Example with Threads
package com.demo; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; public class ConcurrentModificationExceptionDemo extends Thread{ static List<Integer> tempList= new ArrayList<>(); public void run() { try { TimeUnit.SECONDS.sleep(2); tempList.add(4); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { tempList.add(1); tempList.add(2); tempList.add(3); ConcurrentModificationExceptionDemo t = new ConcurrentModificationExceptionDemo(); t.start(); Iterator<Integer> itr = tempList.iterator(); while(itr.hasNext()) { try { TimeUnit.SECONDS.sleep(3); } catch (Exception e) { e.printStackTrace(); } System.out.println(itr.next()); } } }