I have a thread which automatically start up when the application is loaded (load-on-startup).
The thread is querying the database, to see if some jobs have to be startet. The problem is that when I change in the code under development without restarting the web server, a new thread is started. Then I have more threads running and that cause me problems, when the threads write to the database, even if I had all my methods synchronized. How do I ensure that only one thread is allowed to run?
When I stop or restart the web server, I want the single running thread to be killed (removed). How do I ensure that the thread is killed when the web server is stopped or restarted?
How can I use the setDaemon method. I don�t understand the concept? [ September 10, 2005: Message edited by: Jeppe Fjord ]
Joined: Jan 07, 2004
Here is an example of the structure of the code. The thread is running in the servlet. I�m not extending the Thread class and the Runnable interface is not implemented.
Can you switch to using the util Timer? It manages the thread and you manage the tasks that are run on schedule. Keep the timer reference in a stable class that doesn't change, and make the class that changes remove all currently scheduled tasks and schedule new tasks.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Jan 07, 2004
Yes I think that�s a better way to do it. I didn�t knew about the TimerTask.
What about the parameter isDaemon ( new Timer( boolean isDaemon )).
How can you use that?
[ September 11, 2005: Message edited by: Jeppe Fjord ] [ September 12, 2005: Message edited by: Jeppe Fjord ]
Joined: Jan 29, 2003
When you end your main thread and want to stop the program, the JVM will simply terminate any daemon threads. If there are any non-daemon threads it will wait for them to end on their own. I ran into trouble with non-daemon threads that never ended, so the JVM continued to run and show up in task manager when I thought the program was shut down.
I think shutting down with Runtime.exit() will kill daemons and non-daemons just fine. Try it and see!
I am not sure you should be starting threads in a servlet, but if you insist...
Yup, that seems wrong in some way, doesn't it? I don't think the servlet spec gives you any other way to start something at application startup, though, so this is a fairly common "misuse" of the "initialize this servlet at startup" configuration.
There are also cases where we start a new thread at user request, return a "process started" page and do more work in background. It's challenging to get the results of the worker thread back to the user, but do-able.