一个对象引用的思考
一个有趣且令人困惑的代码片段
Code A:
final ConcurrentHashMap<String, Ref> REFS_MAPS = new ConcurrentHashMap<String, Ref>();
public void put(String key) {
Ref ref = new Ref(key, "1");
ref = new Ref(key, "2");
REFS_MAPS.put(key, ref);
}
public Ref get(String key) {
return REFS_MAPS.get(key);
}
它有可能会得到"1"吗?
错误的解释
在多线程调度的情况下,相同的 key 多次同时调用 put 和 get 方法,从 REFS_MAPS 方法 get 时,正好 put 运行到 Ref ref = new Ref(key, "1"),所以就得到了“1”的值,如下所示:

这个解释是错误的,不会得到“1”。
This chapter requires login to view full content. You are viewing a preview.
Login to View Full Content