What is the status of Weak References?

Kevin Gadd kevin.gadd at gmail.com
Sun Feb 3 03:08:44 PST 2013

On Sun, Feb 3, 2013 at 2:58 AM, David Bruant <bruant.d at gmail.com> wrote:
> Let's see how the example would be with weakrefs:
>     function Storage(){
>         var storage = []
>         return {
>             push(e){storage.push(makeWeakRef(e))},
>             last(){
>                 var last = storage[storage.length-1]
>                 return last.get(); // oops!
>             };
>         }
>     }
>     var s = new Storage();
>     s.push({});
>     s.push({});
>     s.last();

What problem is this example supposed to be solving? The problem here
is not weakrefs, the problem is that the problem is poorly specified
and the implementation may be inadequate:
If the goal is to return the most recently pushed item that has not
been collected, then last() must become a for loop that walks
backwards through the storage looking for a live object (preferably
pruning dead ones it encounters). This is a pattern you will see in
applications sometimes - 'weak lists' that contain multiple weak
elements and automatically prune out dead ones to create the illusion
of a sequence only containing live objects.
If the goal is to keep all the objects alive so that last always
returns the last value you pushed, then you wouldn't use weakrefs
The example usage of the Storage class makes no sense to begin with;
the {}'s are effectively dead before they're even placed into storage
because they're temporaries. last would only return something useful
here in the event that the collector didn't take the opportunity to
collect the temporaries (though to be fair, most collectors won't -
they'd probably live in the young generation for a little bit).

When discussing issues as complex as garbage collection, the examples
need to be at least vaguely real-world. Your example does not
demonstrate a limitation of GCs because there's nothing for the GC to
actually do.


More information about the es-discuss mailing list