This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I create a Timer object timer and instantiate it in the init() method in myServlet class.
And there is a stopSampling() method and a startSampling() method to stop and start the timer respectively.
My question is if I stop timer and start timer in turns, then they both work well. But if I start the timer tiwce (call the startSampling() method twice), then call the stopSampling() method, the timer isn't stopped. How can I stop the timer?
You are creating a new TimerTask each time. Either re-use your timer task, or add code to start the timer only if it is not already running.
Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
Joined: Nov 22, 2005
When timer.cancel() is called, all the scheduled tasks associated to the timer will be discarded. Any attempting to use the timer or the TimerTask object will cause an IllegalStateException to be thrown.
So I instantiate a TimerTask and the timer to avoid that. Any way to check the status of the timer and the TimerTask object?
First of all, creating a new Timer is completely unnecessary. You should reuse your Timer and create a new TimerTask instead. Likewise, you should cancel your TimerTask rather than cancelling your Timer. The second issue depends on your requirements:
1. Should it support concurrent sampling? In other words, if more than one call is made to startSampling() prior to a call to stopSampling() should more than one sampling task be started, or should duplicate calls to startSampling() be ignored if it is already sampling?
2. If concurrent sampling is necessary, should it behave in a FIFO or FILO manner? Meaning, should the first task started be the first task stopped, or should the most recent task started be the first task stopped?
If the answer to 1 is no, then you just need a simple flag that you set when sampling is started. Future calls will check this flag and only start sampling if you aren't already. Likewise, when sampling is stopped the flag is reverted and will only attempt to stop sampling if it hasn't stopped already. In this scenario, you can simply create a new TimerTask everytime you start sampling and stop on that TimerTask.
If the answer to 1 is yes, then you will need to keep a collection of tasks started. Each call to start sampling will create a new task and add it to the collection. Each call to stop sampling will pull the first task off the collection and stop it.
One task only:
Multiple with FIFO:
Multiple with FILO would be identical but with an ArrayList and remove() rather than removeFirst().