为什么在Boolean上同步不是一个好习惯?

我的建筑师总是说

永远不要同步布尔值

我无法理解原因,如果有人可以举例说明为什么这不是一个好习惯,我将不胜感激。 参考样本代码

private Boolean isOn = false;

private String statusMessage = "I'm off";

public void doSomeStuffAndToggleTheThing(){

// Do some stuff

synchronized(isOn){

if(isOn){

isOn = false;

statusMessage = "I'm off";

// Do everything else to turn the thing off

} else {

isOn = true;

statusMessage = "I'm on";

// Do everything else to turn the thing on

}

}

}

回答:

我不明白为什么我们应该“从不同步布尔值”

你应该始终synchronize在一个常量对象实例上。如果你在分配的任何对象上进行同步(即,将对象更改为新对象),则该对象不是恒定的,并且不同的线程将在不同的对象实例上进行同步。由于它们在不同的对象实例上进行同步,因此多个线程将同时进入受保护的块,并且会发生竞争情况。这是同步于相同的答案Long,Integer等。

// this is not final so it might reference different objects

Boolean isOn;

...

synchronized (isOn) {

if (isOn) {

// this changes the synchronized object isOn to another object

// so another thread can then enter the synchronized with this thread

isOn = false;

更糟糕的是(如@McDowell指出的)任何Boolean是通过自动装箱创建(isOn = true)是同一个对象Boolean.TRUE(或.FALSE),这是在一个单ClassLoader跨所有对象。你的锁定对象应该在使用该类的类中是本地的,否则,你将锁定与其他类在发生相同错误时可能在其他锁定情况下锁定的同一个单例对象。

如果需要锁定布尔值,则正确的模式是定义一个private final锁定对象:

private final Object lock = new Object();

...

synchronized (lock) {

...

或者,你也应该考虑使用该AtomicBoolean对象,这意味着你可能根本不必synchronize使用它。

private final AtomicBoolean isOn = new AtomicBoolean(false);

...

// if it is set to false then set it to true, no synchronization needed

if (isOn.compareAndSet(false, true)) {

statusMessage = "I'm now on";

} else {

// it was already on

statusMessage = "I'm already on";

}

在你的情况下,由于看起来你需要使用线程来打开/关闭它,所以你仍然需要synchronize在lock对象上设置布尔值,并避免测试/设置竞争条件:

synchronized (lock) {

if (isOn) {

isOn = false;

statusMessage = "I'm off";

// Do everything else to turn the thing off

} else {

isOn = true;

statusMessage = "I'm on";

// Do everything else to turn the thing on

}

}

最后,如果你希望statusMessage可以从其他线程访问,则应将其标记为,volatile除非你synchronize在获取过程中也是如此。

以上是 为什么在Boolean上同步不是一个好习惯? 的全部内容, 来源链接: utcz.com/qa/407091.html

回到顶部