0

假设我有以下(参考页):

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 计时器的事实有关,因此该对象存在于自动局部变量之外?

4

1 回答 1

4

Timer.schedule(int delayMillis)方法将自身(Timer 的实例)添加到 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 解释调度程序线程的评论:

计时器将由一个调度程序线程处理,该线程持有对计时器的引用,因此可以正确地防止它被垃圾收集。

于 2012-08-23T02:27:38.163 回答