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はなぜですか? 自動ローカル変数をガベージ コレクションする必要はありませんか?

これは、HTML タイマーについて話しているため、オブジェクトが自動ローカル変数の外に存在するという事実と関係がありますか?

4

1 に答える 1

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 のコメントから:

タイマーは、タイマーへの参照を保持するスケジューラ スレッドによって処理されるため、ガベージ コレクションが適切に防止されます。

于 2012-08-23T02:27:38.163 に答える