简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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