【发布时间】:2012-08-20 19:49:29
【问题描述】:
我正在尝试使用synchronization java 指令在类中实现细粒度同步,即同步尽可能少的代码。我将内联注释代码,以解释我的工作和在代码之后我会问你如何改进代码:
public class MyClass {
private static volatile MyClass singletonInstance = null;
private HashMap<String, Integer> mHashMap = null;
private String mStringA = null;
private String mStringB = null;
// Use double check technique to use synchronization only
// at the first getInstance() invocation
public static MyClass getInstance() {
if (singletonInstance == null) {
synchronized (MyClass.class) {
if (singletonInstance == null)
singletonInstance = new MyClass();
// Initialize class member variables
singletonInstance.mHashMap = new HashMap<String,Integer>();
singletonInstance.mStringA = new String();
singletonInstance.mStringB = new String();
}
}
return singletonInstance;
}
// The following two methods manipulate the HashMap mHashMap
// in a secure way since they lock the mHashMap instance which
// is always the same and is unique
public Integer getIntegerFromHashmap(String key) {
synchronized (mHashMap) {
return mHashMap.get(key);
}
}
public void setIntegerIntoHashmap(String key, Integer value) {
synchronized (mHashMap) {
mHashMap.put(key, value);
}
}
// With the two String members mStringA and mStringB the problem is
// that the instance of String pointed by the member is varied by the
// setter methods, so we can not lock in a fine grained way and we
// must lock on the singletonInstance.
public String getStringA() {
synchronized (singletonInstance) {
return mStringA;
}
}
public String getStringB() {
synchronized (singletonInstance) {
return mStringB;
}
}
public void setStringA(String newString) {
synchronized (singletonInstance) {
mStringA = newString;
}
}
public void setStringB(String newString) {
synchronized (singletonInstance) {
mStringB = newString;
}
}
}
我不喜欢两个String 成员变量的getter 和setter 方法是锁定singletonInstance 可以使试图访问mStringB 的线程等到正在操作mStringA 的线程释放它的锁。在这种情况下你会怎么做?您是否会在MyClass 中创建两个成员变量,如private final Integer mStringALock = new Integer(0) 和private final Integer mStringBLock = new Integer(0),并分别在mStringA 和mStringB 的getter 和setter 方法的同步块中使用它们?
如果您对如何改进上述代码以及针对String 成员变量的细粒度同步提出的变体有一些想法,欢迎您:)
【问题讨论】:
标签: java synchronization locking singleton