I am loading a servlet on start-up in Weblogic container, from which I am spawning a thread which I want to run continuously until the application is up. However on stopping or deleting the application from container is not stopping the spawned thread. Can I please have any suggestion on how to stop this thread on stopping the application. My application is on Java-8.
2 Answers
If you have a single Thread you should use a volatile flag as explained in this flag.
You can take it a step further by switching to ExecutorService to spawn your worker threads and call ExecutorService.shutdown() on the application shutdown. If you don't require a graceful shutdown you can use ExecutorService.shutdownNow() and set Thread.setDaemon(true) flag when creating threads.
Do note that WebLogic server offers a manager to work with server thread pools as per Using Work Managers to Optimize Scheduled Work. If your application is tightly coupled to WebLogic server you might want to use a server thread pool.
- 43,645
- 9
- 78
- 111
Used ServletContextListener instead of plain HttpServlet. Used the contextInitialized() and contextDestroyed() methods for starting and stopping the thread on application start-up and shutdown respectively.
As suggested, I have used ExecutorService for spawning threads.
- 73
- 3
- 14