首先,我有以下(这里是简化的)类:
public class MyClass {
private static Map<String, Object> objects = new HashMap<String, Object>();
public static Object get(String key) {
return objects.get(key);
}
public static void set(String key, Object object) {
objects.put(key, object);
}
}
然后,我想让它变得安全,所以我尝试了如下synchronized
关键字:
public class MyClass {
private static Map<String, Object> objects = new HashMap<String, Object>();
public static synchronized Object get(String key) {
return objects.get(key);
}
public static synchronized void set(String key, Object object) {
objects.put(key, object);
}
}
问题是,synchronized
在我的情况下,关键字是否足够,或者是否有必要添加volatile
一个,即:
public class MyClass {
private static volatile Map<String, Object> objects = new HashMap<String, Object>();
public static synchronized Object get(String key) {
return objects.get(key);
}
public static synchronized void set(String key, Object object) {
objects.put(key, object);
}
}
?