Re: starting threads from servlets
- From: Ross Bamford <ross@xxxxxxxxxxxx>
- Date: Fri, 29 Apr 2005 14:23:36 +0100
On Fri, 2005-04-29 at 05:37 -0700, Fernando wrote:
> Hi,
> i have a problem, i need to start a thread form a servlet, so that it
> keeps running in background, checking some values in DB every minute.
> The problem is that i start the thread from the servlet and firefox
> tab seems to be loading all the time, not allowing me to click on
> other links from the jsp page, because when i do so the thread is
> interrupted.
>
> I've tried to create another class which starts the thread, and call
> it from the servlet, but it's the same story.
>
> The thread should keep executing itself with this loop inside start:
>
> public synchronized void start() {
> while(true) {
> try {
> verificar();//checks something
> sleep(60000);
> } catch (InterruptedException e) {
> //?
> }
> }
> }
>
> I'm not sure if i'm aproaching this from the right view. if i want the
> thread to be always running, is this the right thing to do? and how
> should i start the thread from the servlet?
>
> Thanks.
The above code shouldn't be in the start method, which is running in the
calling (i.e. servlet) thread, which is why the request never returns.
Instead (of extending thread?) the code should be in the run() method of
a runnable. You should then find that your requests return.
You would probably find that your container didn't shutdown properly,
however, or some other such problem, because the JVM would be waiting on
your thread to finish. You could get around that perhaps using a Daemon
Thread, which isn't waited on but terminated at shutdown.
Better than that would be to follow another poster's suggestion, and
have your thread controlled from a ServletContextListener, starting at
stopping it at context start/stop. Keep a reference to the thread, or
better still to a static accessor, in a context attribute.
There is a proviso to all of this - be bloody careful. The servlets
environment is already pretty complex with respect to it's threading,
and you'll need to make sure you are passing things around safely and so
on.
Cheers,
Ross
--
[Ross A. Bamford] [ross AT the.website.domain]
Roscopeco Open Tech ++ Open Source + Java + Apache + CMF
http://www.roscopec0.f9.co.uk/ + info@xxxxxxxxxxxxxxxxxx
.
- References:
- starting threads from servlets
- From: Fernando
- starting threads from servlets
- Prev by Date: Re: HELP - 3D Tutorials anyone?
- Next by Date: Re: Performance of isDirecory()
- Previous by thread: Re: starting threads from servlets
- Next by thread: Getting Pollinate working
- Index(es):
Relevant Pages
|
|