• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

servlet creating a new thread

 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I want my servlet to start a new thread that will call one simple method once a day and sleep the rest of the time and run indefinitely.
At the moment I have got the code for creating the thread in the init() method of the servlet:
public class MyServlet extends HttpServlet implements Runnable
{
private Thread thread = (Thread) null;
public void init()
{
MyServlet app = new MyServlet();
if ( this.thread == null )
{
thread = new Thread ( app );
thread.start();
}
}
}
and then I visit the servlet in the web browser to kick the thing off.
Is this the right way to do this - creating a new instance of the servlet in the init method and spawing a new thread from this?
Many thanks,
Peter
 
Saloon Keeper
Posts: 27763
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Almost.
If you define the servlet as "load on startup" in your server.xml file, init will automatically be run when the appserver starts and you won't have to resort to questionable kludges. Just create the thread in init and store its handle in a class variable.
I often implement this as what I (mis)call a "null servlet". That is, a servlet that launches a thread or gathers resources but has no doGet or doPost code.
The other common practice is if the thread is some sort of batch process "engine", the doGet/Post routine may insert requests into the thread's input queue and/or query a thread for results.
 
reply
    Bookmark Topic Watch Topic
  • New Topic