我正在教授 Java 并发编程,并想向学生演示使用非线程安全数据结构可能出现的问题。我创建了以下程序:
Map<String,String> favoriteFoods = new HashMap<>();
Thread t1 = new Thread(() -> {
favoriteFoods.put("Alice","avocado");
favoriteFoods.put("Bob","banana");
});
Thread t2 = new Thread(() -> {
favoriteFoods.put("Alice","aloysia");
favoriteFoods.put("Carl","candy");
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(favoriteFoods);
从两个不同的线程访问非线程安全的 HashMap。但是,该程序每次运行时都运行良好。
如何更改代码以演示问题?
最佳答案
尝试向具有哈希冲突的 HashMap 添加元素:
import java.util.*;
public class HashMapRaceCondition2 {
public static void main(String[] args) throws Exception {
class MyClass {
int value;
MyClass(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyClass myClass = (MyClass) o;
if (value != myClass.value) return false;
return true;
}
@Override
public int hashCode() {
return 42;
}
@Override
public String toString() {
return "MyClass{" +
"value=" + value +
'}';
}
} // MyClass
Map<MyClass,Integer> map = new HashMap<>();
Thread t1 = new Thread(() -> {
for (int i =0; i < 1000; ++i) {
map .put(new MyClass(i), i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 2000; i < 3000; ++i) {
map.put(new MyClass(i), i);
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(map.size());
}
}
这段代码在我的机器上每执行 5-6 次就会失败一次。
关于java - 如何在 HashMap 中演示竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47586356/