多个工作线程正在从一个队列中进行处理,当数据库发生故障时,它将联系一个主管,然后该主管将锁定所有工作线程并每隔一段时间轮询数据库,直到数据库启动为止,然后它将释放所有线程,以便它们可以继续处理。工作线程可以提前或等待处理,而主管线程可以锁定或解锁。
我正在考虑这样的界面。您将使用什么同步原语? Actor 将是一个很好的解决方案,但我没有时间重写。
public interface Latch {
/**
* This method will cause a thread(s) to only advance if the latch is in an open state. If the
* latch is closed the thread(s) will wait until the latch is open before they can advance.
*/
void advanceWhenOpen();
/**
* Close the latch forcing all threads that reaches the latch's advance method to wait until
* its open again.
*/
void close();
/**
* Opens the latch allowing blocked threads to advance.
*/
void open();
boolean isOpen();
}
最佳答案
你想要的并不是真正的“闩锁”——至少《Java并发实践》一书中说“一旦闩锁达到终止状态,它就不能再次改变状态,因此它永远保持打开状态。”
但是您可以在后台使用 CountDownLatch 对象 - 每当您的“Latch”需要关闭时,您就可以创建一个新的 CountDownLatch 对象,其计数为 1 并在 advanceWhenOpen() 中启用 wait()。我认为从可读性的角度来看,这将是最好的解决方案。
关于java - 当数据库关闭时阻止工作线程的最佳同步策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28633465/