Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Timer Question

 
Khaled Mahmoud
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am using a timer that runs every 10 seconds. The TimerTask functionality
I implemented starts three threads every time the timer runs.

If those threads did not finish executing within 10 second, another
timer interval will start and three new threads will start. As over all,
I will have at least six threads in the JVM.

My question : How can i prevent overlapping of timer intervals.Which
I do not the second interval to start if there is a thread from the
first interval still running.

As an initial solution I am using Thread.activeCount to check
wether the number of active threads exceend a certain limit. Of so, I
end run function of the TimerTask by a return statement.

What do you think
[ September 18, 2007: Message edited by: Khaled Mahmoud ]
 
Henry Wong
author
Marshal
Pie
Posts: 21498
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question : How can i prevent overlapping of timer intervals.Which I do not the second interval to start if there is a thread from the first interval still running.


A Timer is single threaded -- which means the timer will not be able to call the repeated task again til the previous call finishes. If your timer task performs a join() of the three threads that it starts, the timer will not be able to call the task again, until the three threads finish.

Henry
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What henry told is perfect.
Actually, creating 3 new threads every time the scheduled task is executed, does not look like a good choice. You can use a thread pool instead and restrict the maximum size to 3.
If you are using jdk 5 then, instead of timer you can use a ScheduledThreadPoolExecutor that extends the features of a Timer to provide a thread pool also.
[ September 18, 2007: Message edited by: Nitesh Kant ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the Timer doc for fixed delay vs fixed interval. Do you really want to start a new task before the previous one finishes? You can if you like, or you can choose not to.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic