[MacRuby-devel] WeakRef advice

Charles Oliver Nutter headius at headius.com
Fri Feb 18 15:29:53 PST 2011


Another important use of weakrefs came to mind: avoiding finalization.

In general, finalizers are a bad idea. They often block GC, or at
least block each other. They add overhead to GC cycles, since either
finalizers must be run or objects must be enqueued for another thread
to run their finalizers. By using WeakReferences (and especially
PhantomReferences) you can drive finalization from userland code,
avoiding much of the GC overhead that might otherwise result.

- Charlie

On Fri, Feb 18, 2011 at 5:28 PM, Charles Oliver Nutter
<headius at headius.com> wrote:
> On Tue, Feb 15, 2011 at 5:28 PM, Laurent Sansonetti
> <lsansonetti at apple.com> wrote:
>> Hi Alan,
>> Do you control the data structure that holds a reference to 'B'? If yes, you
>> may want to use NSHashTable which supports weak references.
>> To me, this sounds like a design problem. Maybe your project can be
>> re-architectured to avoid this pattern.
>
> Weak references and weak lists/hashes are often very useful for caches
> you need to age out or when you need to associate data with a given
> instance of an object without holding hard references. Using weak
> references is definitely not a design problem in itself.
>
> I'm also disappointed that you'd recommend people use NSHashTable
> rather than just fixing WeakRef :) In JRuby, we nuked weakref.rb some
> time ago because it has a lot of problems. Instead, we wrap the JVM's
> builtin weakrefs.
>
> See also the weakling gem, which (for JRuby) provides additional
> features mentioned in that Ruby redmine ticket like reference queues
> and a simple weak ID hash to use in place of _id2ref.
>
> - Charlie
>


More information about the MacRuby-devel mailing list