假设我有以下内容 ( 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);
}
}
为什么在方法onClick
退出后Timer仍然存在?自动局部变量不应该被垃圾收集吗?
这是否与我们正在讨论 HTML 计时器以及对象存在于自动局部变量之外的事实有关?
最佳答案
Timer.schedule(int delayMillis)
方法将自身(Timer 的实例)添加到计时器列表中(源代码来自 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
}
<小时/>
摘自 @veer 解释调度程序线程的评论:
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.
关于java - GWT 计时器生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083437/