对于像你这样简单的例子,在setter中只有一个字段并且没有复杂的逻辑来真正要求互斥,你可以只声明该字段volatile
并删除synchronized
关键字。
对于更复杂的东西,你可以使用便宜的读写锁模式:
public class CheapReadWriteLockPattern {
// SINGLE-FIELD:
private volatile Object obj;
public Object read() {
return obj;
}
public synchronized void write(Object obj) {
this.obj = obj;
}
// MULTI-FIELD:
private static class Ref {
final Object x;
final Object y;
final Object z;
public Ref(Object x, Object y, Object z) {
this.x = x;
this.y = y;
this.z = z;
}
}
private volatile Ref ref = new Ref(null, null, null);
public Object readX() { return ref.x; }
public Object readY() { return ref.y; }
public Object readZ() { return ref.z; }
public synchronized void writeX(Object x) {
ref = new Ref(x, ref.y, ref.z);
}
public synchronized void writeY(Object y) {
ref = new Ref(ref.x, y, ref.z);
}
public synchronized void writeZ(Object z) {
ref = new Ref(ref.x, ref.y, z);
}
}