vendredi 22 avril 2016

ServletContextListener contextDestroyed won't interrupt thread

I want to interrupt thread that is started by ServletContextListener, but after i undeploy web application contextDestroyed method is called and interrupt() over thread is executed but thread is still working.

ServletContextListener

public class WebListener implements ServletContextListener {

    MyThread myThread;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();

        context.setAttribute("Users", users);
        myThread = new MyThread();
        myThread.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        sce.getServletContext().removeAttribute("Users");
        myThread.interrupt();
    }
}

Thread Class

public class MyThread extends Thread {

    public MyThread() {

    }

    @Override
    public void interrupt() {
        super.interrupt(); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void run() {
        while (true) {
            doWork();

            try {
                sleep(10000);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    @Override
    public synchronized void start() {
        super.start(); //To change body of generated methods, choose Tools | Templates.
    }

}




Aucun commentaire:

Enregistrer un commentaire