In following code snippet, I tried with both Hashtable
which is so called as thread safe and HashMap
. But in both the cases I am getting ConcurrentModificationExceptionn
. If this is so, then what is the advantages of HashTable
over HashMap
in case of thread safety
public class multiThreadedEnv {
static Map<Integer, String> map = new Hashtable<Integer, String>();
//static Map<Integer, String> map = new HashMap<Integer, String>();
static{
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.put(4, "Four");
map.put(5, "Five");
}
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run() {
Iterator itr= map.entrySet().iterator();
while(itr.hasNext()){
Entry<String,String> entry=(Entry<String, String>) itr.next();
System.out.println(entry.getKey()+" , "+entry.getValue());
itr.remove();
Thread.sleep(2000);
}
}
};
Thread t2= new Thread(){
public void run() {
Iterator itr= map.entrySet().iterator();
while(itr.hasNext()) {
Entry<String,String> entry=(Entry<String, String>) itr.next();
System.out.println(entry.getKey()+" , "+entry.getValue());
itr.remove();
Thread.sleep(2000);
}
}
};
t1.start();
t2.start();
}
}