我正在尝试使用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
释放其锁定。在这种情况下你会怎么做?你会创建两个像private final Integer mStringALock = new Integer(0)
and private final Integer mStringBLock = new Integer(0)
in这样的成员变量,并分别在MyClass
and 的 getter 和 setter 方法的同步块中使用它们吗?mStringA
mStringB
如果您对如何改进上述代码以及成员变量的细粒度同步的建议变体有一些想法String
,欢迎您:)