简体   繁体   English

如果我知道线程名称,如何检查tomcat中的线程是否仍然存在?

[英]How to check if a thread is still alive in tomcat if I know the thread name?

I have an application running on tomcat and I have a static pool ( HashMap ) where I am storing an object each time a thread is created in tomcat through a request and I am deleting the entry from the HashMap when the thread dies. 我有一个在tomcat运行的应用程序,并且有一个static池( HashMap ),每次通过请求在tomcat创建线程时,我都会在其中存储对象,并且在线程死后从HashMap删除条目。 Just to make it clear here is a simple example of what I am doing. 只是为了清楚起见,这是我正在做的一个简单示例。

This is my pool 这是我的游泳池

public class CustomerPool{

    public static Map<String, Customer> customerPool = new HashMap<String, Customer>();

    public static void createSession() {
        String threadName = Thread.currentThread().getName();
        Customer c = new Customer();
        customerPool.put(threadName, customer);
    }

    public static void terminateSession(){
        String threadName = Thread.currentThread().getName();
        customerPool.remove(threadName);
    }
}

And my servlet 还有我的servlet

public class CustomerServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        CustomerPool.createSession();

        //the rest of my code

        CustomerPool.terminateSession();
        return;
    }
}

Due to some exceptions that I am receiving (which are specific to my application and there not point to list them) I believe that sometimes entries are not getting removed from the pool. 由于我收到一些异常(特定于我的应用程序,因此没有指向它们的列表),我认为有时条目不会从池中删除。

I want to produce a report of the pool which will show how many entries are currently into the pool and for which of them the thread does not exist. 我想生成一个池的报告,该报告将显示池中当前有多少个条目以及线程不存在于哪个条目中。 Is it possible in Java to check if a thread is alive by knowing only the thread name? Java中是否可以仅知道线程名称来检查线程是否存在?

Thanks a lot 非常感谢

You should be using a ThreadLocal for this. 您应该为此使用ThreadLocal If the thread dies, the ThreadLocal will be cleaned up automatically since it's a class variable for the Thread. 如果线程死亡,则ThreadLocal将被自动清理,因为它是Thread的类变量。

You can enumerate all the threads in the JVM, but it has a code 'smell' to me if you have to do that for proper function of your program. 您可以枚举JVM中的所有线程,但是如果您必须执行此操作以确保程序正常运行,它会对我有一个“气味”。

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

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