java - 当数据库关闭时阻止工作线程的最佳同步策略

标签 java multithreading

多个工作线程正在从一个队列中进行处理,当数据库发生故障时,它将联系一个主管,然后该主管将锁定所有工作线程并每隔一段时间轮询数据库,直到数据库启动为止,然后它将释放所有线程,以便它们可以继续处理。工作线程可以提前或等待处理,而主管线程可以锁定或解锁。

我正在考虑这样的界面。您将使用什么同步原语? 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/

相关文章:

java - SWIG C++ 到 Java - 包装枚举指针(按引用传递)

java - 如何仅在 Java 中将相同长度的 BitSet 设置为 true 的索引处对 int[] 进行排序

c++ - 如何在多线程中使用QTcpSocket?

multithreading - 线程中的 Perl 内存泄漏(线程不释放内存)

python - 地址已在twisted 中与多线程服务器一起使用

c# - 如何在 C# 中等待单个事件,超时和取消

java - 我们可以使用 Java selenium 代码进行 .net Web 应用程序测试吗?

java - 将 bundle Assets 的文件路径传递到 Android 上的外部库

java - 为什么当我输入非整数输入时我的代码会运行到无限循环?

java - 关于并行运行线程并在之后返回