Java- Why this program not throwing concurrent Modification exception

谁说我不能喝 提交于 2019-12-10 15:12:54

问题


I am trying to induce a concurrent modification exception by accessing a HashMap instance variable reference, but this program is not throwing the error. Appreciate if you could help me to understand.

package Threads;
import java.util.HashMap;

public class ProducerConsumer {

    private HashMap<String, String> sharedMap = new HashMap<String,String>();

    public void putMethod(){

        for (int count=0; count<100; count++)
        {
        System.out.println("Adding into sharedMap:"+count);
        sharedMap.put(Integer.toString(count),Integer.toString(count));
        }
    }

    public static void main(String [] args) throws InterruptedException{

    final ProducerConsumer pc1=new ProducerConsumer();
    Thread t1= new Thread( new Runnable(){

        @Override
        public void run() {
            pc1.putMethod();
        }

    });

    Thread t2= new Thread( new Runnable(){

        @Override
        public void run() {
            pc1.putMethod();
            }   
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    }
}

回答1:


The add() method does not detect concurrent modifications and therefore will not throw a ConcurrentModificationException (that's what anonymous already said).

However, concurrent access to a HashMap can be dangerous, though. Read more about this in another post.

You can enforce a ConcurrentModificationException if you read from the HashMap in parallel:

...
public void putMethod() { ... }
public void iterateMethod() {
    sharedMap.keySet().stream().forEach((s) -> {
        System.out.println("Read key " + s);
    }
}

public static void main(String[] args) throws InterruptedException {
    ...
    t1.start();
    Thread.sleep(20); // sleep time depends on your computer's speed ;-)
    t2.start();
    ...
}
...



回答2:


The exception needs to be thrown by the implementing method that is being invoked on the class. From the Javadoc, it looks like the HashMap Iterators are fast-fail Iterators; meaning it will throw it if you are Iteratoring while adding. The add method will add the item to the map if the key doesn't exist or replace it if it does, I don't think that would throw the exception you're trying to produce.



来源:https://stackoverflow.com/questions/29965956/java-why-this-program-not-throwing-concurrent-modification-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!