Jeremy Manson,Java 内存模型之神,在这个话题上有三个部分的博客-因为本质上你是在问“访问一个不可变的 HashMap 是否安全”-这个问题的答案是肯定的。但是你必须回答这个问题的谓词“ Is my HashMap immutable”。答案可能会让你感到惊讶—— Java 有一套相对复杂的规则来确定不可变性。
public static final HashMap<String, String> map = new HashMap<>();
static {
map.put("A","A");
}
下面的代码将被保存,因为易失性的写入将负责同步。
class Foo {
volatile HashMap<String, String> map;
public void init() {
final HashMap<String, String> tmp = new HashMap<>();
tmp.put("A","A");
// writing to volatile has to be after the modification of the map
this.map = tmp;
}
}
@ThreadSafe
public class SafeStates {
private final Map<String, String> states;
public SafeStates() {
states = new HashMap<String, String>();
states.put("alaska", "AK");
states.put("alabama", "AL");
...
states.put("wyoming", "WY");
}
public String getAbbreviation(String s) {
return states.get(s);
}
}