gpt4 book ai didi

java - 这个并发的遗留代码是否需要可变

转载 作者:行者123 更新时间:2023-12-03 13:09:15 25 4
gpt4 key购买 nike

我正在努力处理一些并发的遗留代码,并且想知道stopLatch和/或mode是否应为volatile:

public class MyClass {

private final ExecutorService executor = Executors.newSingleThreadExecutor();
private MyModeEnum mode = MyModeEnum.NONE;
private CountDownLatch stopLatch;

public synchronized void start(final MyModeEnum mode) {
assert mode != null && mode != MyModeEnum.NONE;
if (isRunning()) {
// Throw an exception.
}
this.mode = mode;
stopLatch = new CountDownLatch(1);
executor.execute(() -> {
try {
// Pre and post operations not under control around stopLatch.await().
} catch (final Exception e) {
stop();
// Further exception handling.
} finally {
MyClass.this.mode = MyModeEnum.NONE;
}
});
}

public synchronized void stop() {
if (!isRunning()) {
return;
}
stopLatch.countDown();
}

public boolean isRunning() {
return mode != MyModeEnum.NONE;
}

public MyModeEnum getMode() {
return mode;
}

}

详细的解释非常感谢。

编辑:我无法将一般问题/答案(例如 When exactly do you use the volatile keyword in Java?)归结为这个特定问题。

最佳答案

根据最受好评的评论:

  • Mick Mnemonic:

    isRunning() is not synchronized, so mode should be volatile.


  • Brian Goetz:

    You have data races on mode. It is accessed from outside the sync block. First choice should be to synchronize isRunning and getMode; making mode volatile is a more advanced play. (Walk first, then fly.)


  • 关于java - 这个并发的遗留代码是否需要可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164162/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com