This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes Timer starts twice when it should start only once Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Timer starts twice when it should start only once" Watch "Timer starts twice when it should start only once" New topic
Author

Timer starts twice when it should start only once

Egil Poma
Ranch Hand

Joined: Nov 23, 2002
Posts: 40
I have a Timer that runs as a deamon. To this Timer I add one single TimerTask to run each 60 sec. The Timer is instantiated by the init() method of a servlet at application startup.

The problems is that the Timer starts TWO different threads with the TimerTask. Both threads run once every 60 sec, and simingly with about 5 seconds between them.

This is very strange because as far as I can see my code should only start ONE thread. What might be wrong? What can I do to make sure the timer only starts ONE thread?

Here's my code (a bit simplified):



This should be a fairly simple setup of a Timer, and I can't understand why it would start two separate threads with the TimerTask!?

As a note I can mention that in my application there's another Timer in another class (which has nothing to do with this class). It is possible to have more than one Timer within the same JVM, right?

Hope somone can help!
[ November 19, 2006: Message edited by: Egil Poma ]
Egil Poma
Ranch Hand

Joined: Nov 23, 2002
Posts: 40
I put some more debug statements into the code, and the servlet init method gets run twice when the application starts up (tomcat).

How on earth can that be?
Egil Poma
Ranch Hand

Joined: Nov 23, 2002
Posts: 40
I found out why the init metod gets run twice ; I'm running tomcat and apache connected, and that causes all init methods to be run twice.

As described here:
http://mail-archives.apache.org/mod_mbox/tomcat-users/200204.mbox/%3CHFEAJGDFPPNOMHMMIKEDMENMCFAA.andy.eastham@gliant.com%3E

So I'm thinking to create a static instance of the MailPoller class in a different class, and then just check if it's null in the init method before making an instance of it.

But will making a static instance of the MailPoller be thread safe?
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Timer starts twice when it should start only once
 
Similar Threads
Timer Process
How to stop a Timer after it's run more than once?
How to run a java application every 30 seconds?.
Timer/ TimerTask
Timer starts twice when it should start only once