我试图用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;
}
}
}
我不喜欢两个的getter和setter方法String
成员变量是锁定在singletonInstance
可以让一个线程试图访问mStringB
等到被操纵线程mStringA
释放其锁。 你会在这种情况下怎么办? 请问你创建了两个成员变量private final Integer mStringALock = new Integer(0)
和private final Integer mStringBLock = new Integer(0)
中MyClass
和的getter和setter方法synchronized块使用它们mStringA
和mStringB
分别?
如果您有关于如何改进上面的代码,为的细粒度同步变化提出一些想法String
成员变量,欢迎您:)