Can anyone tell me if this is a safe thing to do? I run a countdown timer (CountDownTimer) and when the timer reaches zero it must start again, counting down for, for example, a longer time. To do this I call
timer = new TableCount(nextTime * 1000, 100);
within the onFinish() method.
It runs without problems, but I’m concerned it may cause a memory leak. Should I rather have the timer fire some kind of notification that it is done? Here are the important bits from the activity code:
public class TableActivity extends Activity {
TableCount timer; // the count down timer
protected int nextTime;
...
// somewhere I call this - user clicked the "start" button
timer = new TableCount(nextTime * 1000, 100);
nextTime += 100; // for example
...
public class TableCount extends CountDownTimer
{
public void onFinish() {
... // check if number of iterations has been reached, else:
// start counting down from the next value
timer = new TableCount(nextTime * 1000, 100);
nextTime += 100; // for example
}
}
You will not leak memory since you are simply changing the reference of your single declaration of TableCount to a new timer which implicitly dereferences the previous object.
Even if you did something bizarre like creating a new timer each run and adding it to an array (for example) you would still not leak. You might eventually run out of memory but that’s not the same as leaking since when the activity is finished(), and assuming that you are not holding a static reference somewhere else, then the memory is freed and eligible for garbage collection.
However, why not just reuse the existing timer and use schedule() to run it again?