Contents

Weak references

Object Icon has a builtin type, weakref, which provides a weak reference to a value.

Creating a weak reference

To create a weak reference, use the builtin function weakref as follows :-

w := weakref(x)

where x has one of the following permitted types :-

Now w will have the type “weakref”, and image(w) will produce something like this :-

weakref#1(list#31(3))

with the image of the inner value (in this case a 3-element list) being shown within the parentheses.

Accessing the value

To access the inner value, use the builtin function weakrefval, as follows :-

y := weakrefval(w)

At some point in the future the weak reference may hold the last reference to the inner value. When this is detected during a garbage collection, the memory used by the inner value is reclaimed, and the weak reference is cleared. Thereafter, weakrefval will fail.

This is illustrated with the following interaction in ieval :-

> l := [1,2,3]
list#11622[1,2,3]
> w := weakref(l)
weakref#3(
   list#11622[1,2,3]
)
> weakrefval(w)
list#11622[1,2,3]
> collect()
&null
> w
weakref#3(
   list#11622[1,2,3]
)
> l := &null
&null
> collect()
&null
> w
weakref#3()
> weakrefval(w)

Note how the first collection doesn’t affect w, since the variable l still has a strong reference to the list. However, after l is set to &null, w does have the last reference. Therefore the second collection clears the weak reference and reclaims the memory used by the list.

WeakrefTable

The datastruct package contains a table-like data structure, datastruct.WeakrefTable. This is like an ordinary table, but its keys are wrapped in weak references. This means that when the key becomes the last reference, it may be deleted from the table after a garbage collection.

The following ieval interaction shows how this works :-

> l := [1,2,3]
list#2734[1,2,3]
> w := WeakrefTable()
object datastruct.WeakrefTable#1()
> w.insert(l, 99)
object datastruct.WeakrefTable#1(
   list#2734[1,2,3]->99
)
> collect()
&null
> w
object datastruct.WeakrefTable#1(
   list#2734[1,2,3]->99
)
> l := &null
&null
> collect()
&null
> w
object datastruct.WeakrefTable#1()

Note how after the second collection, the single key is deleted from the table, leaving it empty.

Contents