Java 如何在中间中断putAll操作以生成ConcurrentModificationException
我想重现一个场景,其中有两个线程访问共享HashMap。当一个线程使用putAll()操作将共享映射的内容复制到localMap时,第二个线程更改共享映射,并应引发CocurrentModificationException 我已经尝试过,但无法在putAll操作运行时重现异常。每次putAll在其他线程进行修改之前完成,或者在其他线程修改之后调用putAll 有人能建议我如何用java生成场景吗Java 如何在中间中断putAll操作以生成ConcurrentModificationException,java,multithreading,collections,concurrentmodification,Java,Multithreading,Collections,Concurrentmodification,我想重现一个场景,其中有两个线程访问共享HashMap。当一个线程使用putAll()操作将共享映射的内容复制到localMap时,第二个线程更改共享映射,并应引发CocurrentModificationException 我已经尝试过,但无法在putAll操作运行时重现异常。每次putAll在其他线程进行修改之前完成,或者在其他线程修改之后调用putAll 有人能建议我如何用java生成场景吗 谢谢 旋转两个线程,让它们连续运行 让一个线程不断地执行putAll,另一个线程不断地进行修改。i
谢谢 旋转两个线程,让它们连续运行 让一个线程不断地执行putAll,另一个线程不断地进行修改。
import java.util.HashMap;
import java.util.HashMap;
import java.util.Map;
public class Example {
private final HashMap<String, String> map = new HashMap<String, String>();
public static void main(String[] args) {
new Example();
}
public Example() {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
int counter = 0;
while (true) {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put("example" + counter, "example");
counter++;
map.putAll(tmp);
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
map.values().remove("example");
}
}
});
thread1.start();
thread2.start();
}
}
导入java.util.Map;
公开课范例{
private final HashMap map=new HashMap();
公共静态void main(字符串[]args){
新例子();
}
公共示例(){
Thread thread1=新线程(new Runnable(){
@凌驾
公开募捐{
int计数器=0;
while(true){
Map tmp=newhashmap();
tmp.put(“示例”+计数器,“示例”);
计数器++;
普塔尔地图(tmp);
}
}
});
Thread thread2=新线程(new Runnable(){
@凌驾
公开募捐{
while(true){
map.values().remove(“示例”);
}
}
});
thread1.start();
thread2.start();
}
}
不幸的是,我无法直接从当前工作站复制/粘贴正在运行的代码,因此我在此处重新键入了代码,因此可能会出现键入错误
如您所见,第一个线程在不断添加值,而第二个线程在映射中迭代值。当它开始迭代这些值时,它需要一些值(该值在构造迭代器时初始化)。但是,由于thread1不断添加项,因此当迭代器在实际执行删除代码时检查映射中的实际值时,该值与预期值不同。这会导致ConcurrentModificationException。如果您只需要抛出一个
CocurrentModificationException
,您可以实现自己的Map
实现(HackedMap
)当HashMap
试图从您的HackedMap
复制值时,从HashMap
中删除项目