This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Canceling a TimerTask Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Canceling a TimerTask" Watch "Canceling a TimerTask" New topic
Author

Canceling a TimerTask

Jean-Michel Vilain
Greenhorn

Joined: Aug 06, 2010
Posts: 17

Hi ranch people!
I'm into server side multithreading and I'm finding it puzzlingly amusing.
I create a Timer and use it to schedule a TimerTask via schedule(TimerTask t, int delay), i.e. this TimerTask is meant to trigger once at most.
In the case where the TimerTask gets canceled, is this safe not keeping a reference to the Timer? Because I won't be able to call stop or anything on it when the TimerTask gets canceled.
Thoughts or suggestions welcome!


Designer and developer on Faëria: Strategy Card Game (www.faeria.net). The server is 100% Java.
@Jiem_ on Twitter (http://twitter.com/Jiem_)
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

The procedure to cancel a TimerTask seems pretty simple to me: you call its cancel() method. You can read the API documentation and confirm that for yourself. So I don't understand the rest of your question.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 407
    
    1

It's safe as the timer lives on until actually removed by the scheduler (happens automatically) when cancelled so if your not worried about performance your fine . Cancelled timers can seriously mess with GC performance (consider purge), though only worry about this if your writing serious server apps and use timers a lot.


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
 
Don't get me started about those stupid light bulbs.
 
subject: Canceling a TimerTask
 
Similar Threads
Help needed with java.util.Timer
Executing a fn every hour
Design Help required
[Need recommendation] Do a repetitive task daily
How to avoid IllegalStateExceotion in Timer