GWT计时器生命周期

时间:2012-08-23 01:09:01

标签: java gwt timer

假设我有以下内容(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退出后,计时器如何仍然存在?自动局部变量不应该被垃圾收集吗?

这是否与我们讨论HTML计时器的事实有关,因此该对象存在于自动局部变量之外?

1 个答案:

答案 0 :(得分:4)

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的评论解释调度程序线程:

  

计时器将由一个持有a的调度程序线程处理   参考定时器,因此 righfully 阻止它   垃圾收集。