aspose file tools*
The moose likes Servlets and the fly likes servlet creating a new thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "servlet creating a new thread" Watch "servlet creating a new thread" New topic
Author

servlet creating a new thread

Peter Straw
Ranch Hand

Joined: Jan 08, 2002
Posts: 79
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
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16250
    
  21

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.


Customer surveys are for companies who didn't pay proper attention to begin with.
 
wood burning stoves
 
subject: servlet creating a new thread