Reputation: 96716
Let's say I have the following (ref page):
public class TimerExample implements EntryPoint, ClickHandler {
public void onModuleLoad() {
Button b = new Button("Click and wait 5 seconds");
b.addClickHandler(this);
RootPanel.get().add(b);
}
public void onClick(ClickEvent event) {
// Create a new timer that calls Window.alert().
Timer t = new Timer() {
@Override
public void run() {
Window.alert("Nifty, eh?");
}
};
// Schedule the timer to run once in 5 seconds.
t.schedule(5000);
}
}
How come the Timer is still around after the method onClick
exits? Shouldn't the automatic local variables be garbage collected?
Does this have to do with the fact we are talking about a HTML timer and thus the object exists outside of the automatic local variables?
Upvotes: 0
Views: 650
Reputation: 2044
The Timer.schedule(int delayMillis)
method adds itself (the instance of Timer) to a List of Timers (source code from 2.5.0-rc1):
/**
* Schedules a timer to elapse in the future.
*
* @param delayMillis how long to wait before the timer elapses, in
* milliseconds
*/
public void schedule(int delayMillis) {
if (delayMillis < 0) {
throw new IllegalArgumentException("must be non-negative");
}
cancel();
isRepeating = false;
timerId = createTimeout(this, delayMillis);
timers.add(this); // <-- Adds itself to a static ArrayList<Timer> here
}
From comment by @veer explaining the scheduler thread:
The timer is going to be handled by a scheduler thread that holds a reference to the Timer and thus righfully prevents it from being garbage collected.
Upvotes: 4