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 and stops when the Application Server closes.
How would I go about doing this? It's not really a Session Bean or MDB. It's just a thread.
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':
<listener>
<listener-class>atis.Listener</listener-class>
</listener>
Don't know whether this kind of thing is recommended or not, but it has worked fine for me in the past.