Reputation: 349
I was studying about fail fast and fail safe iterators and I had this question in mind. I am not sure if my understanding is correct.
Vector is synchronized thread safe collection object in Java. So when I try to get the iterator of vector it is a fail fast iterators which means . . When I use this iterator on vector object and any changes made to the vector it will throw ConcurrentModificationExeption. But since vector is thread safe it should be provided with fail safe iterators.
Why is not the case in Java with vector. Where as with concurrentHashMap it is provided with thread safe iterators.
Upvotes: 0
Views: 1817
Reputation: 21
Yes ,Vector is Thread safe as well as iteration of vector is fail safe.It is a legacy class which is introduce into 1.0 version then later .Sun people did refractory engineer on that and added into List interface so we can use all the method of List interface as well as Vector if we will iterate Vector object using iterator then it will throws concurrentModificationException but if we will iterate vector using Enumeration Interface then it will not throws any concurrent Modification Exception.Example : In this Example main thread is iterating elements from vector and child thread is updating existing vector object and we are not getting any concurrentModificationException
public class MyThread extends Thread{
static Vector<String> vector = new Vector<>();
public static void main(String[] args) {
vector.add("Sachine");
vector.add("Rahul");
vector.add("Virat");
vector.add("Dhoni");
vector.add("Manish");
MyThread t = new MyThread();
t.start();
Enumeration<String> it = vector.elements();
while (it.hasMoreElements()) {
String name = (String) it.nextElement();
System.out.println(name);
}
System.out.println(vector);
}
@Override
public void run() {
vector.add("Shikhar");
}
}
Upvotes: 2