简体   繁体   English

正常关闭包含连接的Java任务

[英]Gracefully shutting down a Java task which contains a connection

I have a number of Runnable tasks governed by an executor service. 我有许多由执行程序服务管理的可运行任务。

These tasks are essentially JMS queue pollers and contain their own connections. 这些任务本质上是JMS队列轮询器,并且包含它们自己的连接。

For example: 例如:

ExecutorService executor = Executors.newFixedThreadPool(...);
executor.submit(new MyListener());

My listener: 我的听众:

public class MyListener implements Runnable {
    @Override
    public void run() {
        // Create my JMS connection here
    }
}

How do I gracefully close the JMS connection in each task and then proceed to shutdown each thread? 如何在每个任务中正常关闭JMS连接,然后继续关闭每个线程?

I'm having problems shutting down the executor service with shutdown() . 我在使用shutdown()关闭执行程序服务时遇到问题。

I need to force an interrupt with shutdownNow() , however, how can I be sure that my JMS connection has been closed without me explicitly calling .close() ? 我需要使用shutdownNow()强制执行中断,但是,如何在没有显式调用.close()情况下确保我的JMS连接已关闭?

Is there an interface I'm missing that allows shutdown hooks to be executed when I attempt to stop the task? 我是否缺少接口,允许在尝试停止任务时执行关机挂钩?

The easiest would be to use an atomic boolean shared by the class that signals shutdown and the runnable. 最简单的方法是使用由类共享的原子布尔值,该原子量表示关闭和可运行。 This tells them to stop. 这告诉他们停止。 Another option is finding the threads yourself and interrupt them. 另一种选择是自己查找线程并中断它们。 You would need to catch the interrupted exception and close the connection. 您将需要捕获中断的异常并关闭连接。 You can set the thread names when the runnable launch for easy id. 您可以在可运行的启动时设置线程名称以获取简单的id。

Here's my solution to gracefully shutdown threads holding a connection, utilising the suggestion of an atomic boolean: 这是我的解决方案,可以利用原子布尔的建议从容地关闭持有连接的线程:

MyRunnable implements Runnable {

    private volatile boolean isActive = true;

    public void run() {
       while(isActive && !Thread.currentThread().isInterrupted()) {
           ...
       }
    }

    public void stop() {
        isActive = false;
    }
}

Main thread: 主线程:

private void myShutdownHook() {
    myRunnableInstance.stop();

    // Can safely shutdown executor now...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM