如何在Tomcat停止时停止执行程序线程? [英] How to stop an executor thread when Tomcat is stopped?

查看:2096
本文介绍了如何在Tomcat停止时停止执行程序线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过创建固定数量的线程来执行HTTP GET数据检索来使用执行程序服务。

I am using an executor service by creating a fixed number of threads to do a HTTP GET data retrieval.

executorService = ExecutorServiceFactory.getInstance().getExecutorService(Config.getInstance().getNumberOfThreads(), "ThreadExecutor_"+UIDFactory.getInstance().createSessionID());
executorService.execute(new Retrieve(data));

private class Retrieve implements Runnable{
    private Vector<String> data;

    public WADORetrieve(Vector<String> data) {          
            this.data = data;
    }

    @Override
    public void run() {
        for(int i=0;i<data.length;i++){
            fetch(data[i]);
        }
    }
}    

当Tomcat停止时我们得到这个错误:

When Tomcat is stopped we get this error:


严重:Web应用程序[/ viewer]似乎已经启动了一个名为[ThreadExecutor_5161616156]但未能阻止它的线程。这很可能会造成内存泄漏。

SEVERE: The web application [/viewer] appears to have started a thread named [ThreadExecutor_5161616156] but has failed to stop it. This is very likely to create a memory leak.

这是一个真正的问题吗?如果没有这些服务错误,我该怎么做才能正常停止tomcat。

Is this a real issue? What can I do to stop tomcat properly without these service errors.

推荐答案

这是一个真正的问题。执行程序汇集的非守护程序线程不会自行消失,如果不在执行程序上调用shutdown,则线程将保持活动状态并阻止JVM退出。

It's a real problem. Non-daemon threads pooled by your executor don't go away by themselves, if you don't call shutdown on the executor then the threads will stay alive and prevent the JVM from exiting.

创建一个ServletContextListener,在 contextDestroyed 上调用执行器上的shutdown。

Make a ServletContextListener that calls shutdown on your executor on contextDestroyed.

或者你可以创建线程由ThreadFactory守护程序线程返回,以便在最后一个非守护程序线程终止时它们将退出。由于您正在进行数据检索,因此最好避免这种情况,因为它可能会使数据库资源不公开。

Alternatively you could make the threads returned by your ThreadFactory daemon threads, so that they would exit when the last non-daemon thread terminates. Since you're doing data retrieval it would seem better to avoid this since it could leave database resources unclosed.

这篇关于如何在Tomcat停止时停止执行程序线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆