Java-为什么这个程序不会抛出并发的修改异常 [英] Java- Why this program not throwing concurrent Modification exception
问题描述
我试图通过访问HashMap实例变量引用来诱发并发修改异常,但是这个程序不会抛出错误。非常感谢您能帮助我理解。
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();
}
}
推荐答案
add()
方法不检测并发修改,因此不会抛出 ConcurrentModificationException
(这是匿名已经说的)。
The add()
method does not detect concurrent modifications and therefore will not throw a ConcurrentModificationException
(that's what anonymous already said).
但是,并发访问HashMap可能很危险。 请在另一篇文章中阅读更多信息。
However, concurrent access to a HashMap can be dangerous, though. Read more about this in another post.
如果您从 HashMap
中并行读取,您可以强制执行 ConcurrentModificationException
:
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();
...
}
...
这篇关于Java-为什么这个程序不会抛出并发的修改异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!