File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

servlet creating a new thread

Peter Straw
Ranch Hand

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

Joined: Jun 25, 2001
Posts: 17417

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.

An IDE is no substitute for an Intelligent Developer.
I agree. Here's the link:
subject: servlet creating a new thread
jQuery in Action, 3rd edition