2012-08-23 28 views
0

比方說,我有以下的(ref page):GWT定時器週期

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

Timer.schedule(int delayMillis)方法添加本身(定時器的實例)的定時器列表(源代碼從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說明調度程序線程:

定時器是要通過其保持 參考定時器的調度線程來處理,因此righfully防止它從 垃圾收集。

+1

對。計時器將由一個調度程序線程處理,該線程持有對「Timer」的引用,從而*可以*防止垃圾收集。 – oldrinb

+0

@veer好詳細說明,我已經把它放在底部,如果這對你很好。 – edwardsmatt

+0

沒問題! :-) – oldrinb