Using weak references in ActionScript 3 +
Sometimes you want to keep a weak reference to an object. i.e. you don’t really care if the object is garbage collected, and you don’t want to be the one keeping it from being so, while at the same time you’d like to access it while it’s available.
Here’s a simple class for doing this in ActionScript 3:
public class WeakReference
{
private var reference:Dictionary = new Dictionary(true);
public function WeakReference(object:Object)
{
reference[object] = null;
}
public function getObject():Object
{
for (var object:Object in reference)
return object;
return null;
}
}
It’s an extremely simple implementation, modelled on the
WeakReference class in Java (minus the complexity).
How to use it
Let’s suppose that you’re creating an object foo in one part of your program.
foo = new Foo();
The object is then passed around, especially to another object bar.
bar = new Bar(foo);
bar really doesn’t want to hold on to foo. Instead, it just wants to use it for as long as it’s available (i.e. until you’ve discarded it).
In such a scenario, the class Bar would hold a weak reference to the object passed to it.
public function Bar(foo:Foo)
{
ref = new WeakReference(foo);
}
Methods of Bar might then access foo through the weak reference.
var foo:Foo = ref.getObject() as Foo;
if (!foo) {
// foo has been garbage collected. Forget it.
ref = null;
return;
}
foo.someMethod();
...
If getObject returns null, the object has been garbage collected.
Clearing references
Continuing the example, if the part of the code that created the object
were also to be responsible for freeing it, it would reset its reference
to null when the object was no longer needed.
foo = null;
You could also drop weak references in the same manner.
ref = null;
Now here’s a little oddity: Setting references to null doesn’t
immediately cause the object to be garbage collected; in fact, in my
tests, the object seemed to linger on forever! On the other hand, setting
a reference to undefined does the trick — the object is gone
immediately (getObject returns null).
This behaviour seems to be a bug in the Flash Player, and it has been reported before.
All in all, WeakReference is a handy class. You can use it in your projects.
For more information on weak references in ActionScript 3, see: