java - GWT 计时器生命周期

标签 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退出后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/

相关文章:

java - Gwt 自定义文本框具有气球弹出窗口

GWT 序列化不应返回接口(interface) : what about parameters and contained objects?

Angular Testing - 如果计时器在组件初始化中,则 Tick 不起作用

Java编译器树API : Get fully qualified superclass name

java - 使用 JCIFS 将文件从本地驱动器复制到共享驱动器性能问题

java - 为什么我可以通过 undefined object 的接口(interface)访问对象的方法?

gwt - 如何将 OpenLayers 中的 VectorFeatures 或图层的坐标从一种投影转换为另一种投影?

c - 根据现在的时间运行 func()

php - 定时器 mysql php 检查

java - 如何禁用 GWT 中的代码拆分?