Project

General

Profile

Actions

Feature #6309

open

Add a reference queue for weak references

Added by headius (Charles Nutter) over 12 years ago. Updated about 4 years ago.

Status:
Assigned
Target version:
-
[ruby-core:<unknown>]

Description

Most interesting uses of WeakRef are much harder to do efficiently without a reference queue.

A reference queue, as implemented by the JVM, is basically a queue into which weak references are placed some time after the object they refer to has been collected. The queue can be polled cheaply to look for collected references.

A simple example of usage can be seen in the weakling gem, with an efficient implementation of an ID hash: https://github.com/headius/weakling/blob/master/lib/weakling/collections.rb

Notice the _cleanup method is called for every operation, to keep the hash clear of dead references. Failure to have a _cleanup method would mean the hash grows without bounds.

_cleanup cannot be implemented efficiently on MRI at present because there's no reference queue implementation. On MRI, _cleanup would have to perform a linear scan of all stored values periodically to search for dead references. For a heavily used hash with many live values, this becomes a very expensive operation.

It's probably possible to implement reference queues efficiently atop the new ObjectSpace::WeakMap internals, since it already keeps track of weak references and can run code when a weak reference no longer refers to a live object.


Related issues 1 (1 open0 closed)

Related to Ruby master - Feature #6308: Eliminate delegation from WeakRefAssignedmatz (Yukihiro Matsumoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0