tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Fred Whipple" <fwhip...@imagineis.com>
Subject RE: HOW CAN I USE THREADS IN TOMCAT
Date Sat, 01 Nov 2003 22:01:32 GMT
I would also add that unless you have a particular need to embed this in
a specific Servlet, it might make more sense to add this thread to a
context listener handler.

For example, if I wanted to send out email to 1000 people (not Spam, of
course! ;-) and I initiated this from within a Servlet, in this case I'd
add a thread to the Servlet and let the Servlet return while the email
was still going out.  This assumes I handle any errors in some other way
than displaying the results on the page.

On the other hand, if I wanted to, perhaps, clean-up some temporary data
within a database every so often, and I wanted to include this
funcitonality within a Web app rather than in a separate application
that I run from the CL via Cron every now and then, I'd probably
implement this within a context listener handler so that the thread
starts up when the Web app starts up and continues utnil the Web app
shuts down.

Just a thought!

    -Fred Whipple
     iMagine Internet Services

> -----Original Message-----
> From: Erik Wright [mailto:erik@spectacle.ca] 
> Sent: Saturday, November 01, 2003 11:03 AM
> To: Tomcat Users List
> Subject: Re: HOW CAN I USE THREADS IN TOMCAT
> 
> 
> A servlet is just a Java class. You can do anything you can 
> do with the 
> java language, including start threads. The following starts a thread 
> that runs some task every 10 minutes. The thread is started in the 
> servlet init method. I choose to set the thread to daemon 
> mode, meaning 
> that when the main thread of execution shuts down the mailer 
> thread will 
> automatically be killed. Otherwise you need to be sure to 
> keep track of 
> it and be sure to signal it to shutdown in your 
> Servlet.destroy method.
> 
> public class MyServlet extends HttpServlet
> {
>     private static class MailerThread extends Thread
>     {
>        public void run ()
>        {
>           while (true)
>           {
>               // do something
>              synchronized (this)
>              {
>                 wait (10*60*1000);
>              }
>           }
>        }
>     }
> 
>     // the servlet init method
>     public void init ()
>     {
>        MailerThread thread = new MailerThread ();
>        thread.setDaemon (true);
>        thread.start ();
>     }
> 
>     // ... doGet, etc. ...
> }
> 
> -Erik


---------------------------------------------------------------------
To unsubscribe, e-mail: tomcat-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: tomcat-user-help@jakarta.apache.org


Mime
View raw message