BIT-101 [2003-2017]

Running Timers are not Garbage Collected. Ever.


On a certain mailing list, something was mentioned about Timers, cleaning up, garbage collection, etc. Arno Gourdol from the Adobe AIR Team made the following statement:

Just to be clear: even if you have no references to a Timer, as long as the timer is running, it will not be Garbage Collected (think of it as if the runtime was keeping a reference to running timers).

That was interesting to me, and as it recently came up on another mailing list, I thought I’d do a little test.

Here, I create a Timer and a Sprite as local variables. The timer has a weak-referenced listener for the Timer event, and the sprite has a weak-referenced listener for the enterFrame event. I let them run for a second and then force garbage collection using a trick Grant Skinner mentioned a while back.

At that point, you can see the enterFrame stops firing, as the sprite has been garbage collected and ceases to exist. However, the timer continues running forever, as Arno’s statement predicts.

[as]package {

import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.net.LocalConnection;
import flash.utils.*;

public class TimerTest extends Sprite{

public function TimerTest(){
var timer:Timer = new Timer(30);
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true);
timer.start();

var s:Sprite = new Sprite();
s.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true);

setTimeout(killEm, 1000);
}

private function tick(event:TimerEvent):void
{
trace(“tick”);
}

private function onEnterFrame(event:Event):void
{
trace(“enterFrame”);
}

private function killEm():void
{
trace(“kill…..”);
try
{
new LocalConnection().connect(‘foo’);
new LocalConnection().connect(‘foo’);
}
catch (e:*)
{
}
}
}
}
[/as]

Just thought that was interesting and might come in handy someday.

« Previous Post
Next Post »