Does it iterate over the security of Vector ConcurrentModificationException?
YES . It does an iteration over Vector security with a ConcurrentModificationException . If it is not synchronized, then in this case, if you access Vector through various threads, and some other thread structures the Vector at any time after creating the iterator, the iterator will throw a ConcurrentModificationException . Try running this code:
import java.util.*; class VVector { static Vector<Integer> mapItems = new Vector<Integer>(); static { for (int i = 0 ; i < 200 ; i++) { mapItems.add(i); } } public static void readVector() { Iterator<Integer> iterator = mapItems.iterator(); try { while(iterator.hasNext()) { System.out.print(iterator.next() + "\t"); } } catch (Exception ex){ex.printStackTrace();System.exit(0);} } public static void main(String[] args) { VVector v = new VVector(); Thread th = new Thread( new Runnable() { public void run() { int counter = 0; while ( true ) { mapItems.add(345); counter++; if (counter == 100) { break; } } } }); th.start(); v.readVector(); } }
On my system, the following output is displayed at runtime:
0 1 2 3 4 5 6 7 8 9 java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(Unknown Source) at java.util.AbstractList$Itr.next(Unknown Source) at VVector.readVector(VVector.java:19) at VVector.main(VVector.java:38)
But on the other hand, if you create a code block containing Iterator to access this Vector , synchronized with mapItems as a lock, this will prevent other methods related to Vector from being executed until synchronized completes atomically.
Vishal k
source share