当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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. 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

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?

Thanks a lot

网友答案:

You should be using a ThreadLocal for this. If the thread dies, the ThreadLocal will be cleaned up automatically since it's a class variable for the 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: