After reading throw Daemon threads and implementing according to my requirements raised several doubts.
Please clarify me
-
I am using ServletContextListener class to invoke a Daemon thread which needs to run unitl JVM exits
public void contextInitialized (ServletContextEvent event) { context = event.getServletContext(); //getting from spring context MyServiceManager serviceManager = (MyServiceManager) ctx.getBean("myServiceManager"); serviceManager.setDaemon(true); serviceManager.start(); } -
in ServiceManager class I am running an infinite loop to run the program foever until JVM exists
public void run() { try { startService(); } catch (Exception e) { logger.error("Error Occured in Background Process Runner"); } } private void startService(){ while(true){ try{ //invoke some new threads and do processing jobs until server/jvm stops }catch(Exception e) { //log but don't quit } } } }
The concern is, will daemon thread with the above implmentation runs foever? if not, what should i do to achieve my job. Unless JVM stops (server stopped), tell it to not to quit.
Note: I am trying my level best to format this post. but today something is going, it’s not getting formatted 🙁
Your daemon thread will run until the
run()method terminates, either by exiting normally or by throwing an exception (or until the VM exits, which is what you want). Since you catch all exceptions thrown bystartService(), it will run untilstartService()returns or throws an exception, and will then exit normally.Be aware that if
startService()is interrupted while it is waiting for I/O, sleeping, or in a wait state, then it will generally throw anInterruptedException. Well-behaved threads usually exit when they are interrupted, as this is the normal method for telling a thread to exit.Note that marking the thread as a daemon only means that the VM will not wait until the thread exits before it shuts down. None of the other behavior regarding thread termination is affected by the thread being a daemon or not.