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?
The
Timer.schedule(int delayMillis)method adds itself (the instance of Timer) to a List of Timers (source code from 2.5.0-rc1):From comment by @veer explaining the scheduler thread: