Threading in an Application Server

前端 未结 6 1248
礼貌的吻别
礼貌的吻别 2021-02-19 21:41

I have a Java program/thread that I want to deploy into an Application Server (GlassFish). The thread should run as a \"service\" that starts when the Application Server starts

6条回答
  •  有刺的猬
    2021-02-19 22:04

    I've only done this with Tomcat, but it should work in Glassfish.

    Create a Listener class that implements javax.servlet.ServletContextListener, then put it in web.xml. It will be notified when your web app is started and destroyed.

    A simple Listener class:

    public class Listener implements javax.servlet.ServletContextListener {
    
        MyThread myThread;
    
        public void contextInitialized(ServletContextEvent sce) {
            myThread = new MyThread();
            myThread.start();
        }
    
        public void contextDestroyed(ServletContextEvent sce) {
            if (myThread != null) {
                myThread.setStop(true);
                myThread.interrupt();
            }
        }
    
    }
    

    This goes in web.xml after your last 'context-param' and before your first 'servlet':

    
        atis.Listener
    
    

    Don't know whether this kind of thing is recommended or not, but it has worked fine for me in the past.

提交回复
热议问题