控制启动时的竞争条件 [英] Controlling race condition at startup
问题描述
我有一些代码,我想有一些时间进行初始化。但是这个代码没有一个明确的生命周期,所以我的逻辑可能被潜在地由多个线程调用之前我的初始化完成。所以,我想基本上确保我的逻辑代码等待,直到初始化完成。
I have some code that I want to have some one time initialisation performed. But this code doesn't have a definite lifecycle, so my logic can be potentially invoked by multiple threads before my initialisation is done. So, I want to basically ensure that my logic code "waits" until initialisation is done.
这是我的第一次切割。
public class MyClass {
private static final AtomicBoolean initialised = new AtomicBoolean(false);
public void initialise() {
synchronized(initialised) {
initStuff();
initialised.getAndSet(true);
initialised.notifyAll();
}
}
public void doStuff() {
synchronized(initialised) {
if (!initialised.get()) {
try {
initialised.wait();
} catch (InterruptedException ex) {
throw new RuntimeException("Uh oh!", ex);
}
}
}
doOtherStuff();
}
}
我基本上希望确保这样做我认为它会做 - 阻塞doStuff直到初始化是真的,我不缺少一个竞争条件,其中doStuff可能会卡在一个Object.wait()永远不会到达。
I basically want to make sure this is going to do what I think it's going to do -- block doStuff until the initialised is true, and that I'm not missing a race condition where doStuff might get stuck on a Object.wait() that will never arrive.
编辑:
我无法控制线程。我想要能够控制何时所有的初始化完成,这就是为什么doStuff()不能调用initialise()。
I have no control over the threads. And I want to be able to control when all of the initialisation is done, which is why doStuff() can't call initialise().
我使用AtomicBoolean它是一个值持有者和我可以同步的对象的组合。我可以简单地有一个public static final Object lock = new Object();和一个简单的布尔标志。 AtomicBoolean方便地给了我两个。不能修改布尔值。
I used an AtomicBoolean as it was a combination of a value holder, and an object I could synchronize. I could have also simply had a "public static final Object lock = new Object();" and a simple boolean flag. AtomicBoolean conveniently gave me both. A Boolean can not be modified.
CountDownLatch正是我在寻找的。我也考虑使用一个Sempahore 0许可证。但CountDownLatch是完美的只是这个任务。
The CountDownLatch is exactly what I was looking for. I also considered using a Sempahore with 0 permits. But the CountDownLatch is perfect for just this task.
推荐答案
这是库的一个奇怪的混合和内置的并发控制。这样的东西很干净:
That's a strange mix of library and built-in concurrency controls. Something like this is much cleaner:
public class MyClass {
private static final CountDownLatch latch = new CountDownLatch(1);
public void initialise() {
initStuff();
latch.countDown();
}
public void doStuff() {
try {
latch.await();
} catch (InterruptedException ex) {
throw new RuntimeException("Uh oh!", ex);
}
doOtherStuff();
}
}
这篇关于控制启动时的竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!