[swift-evolution] Proposal: Give weak references the ability to notify reference-holders when they transition to nil
gparker at apple.com
Mon Dec 14 15:06:12 CST 2015
> On Dec 13, 2015, at 6:24 PM, Michael Henson via swift-evolution <swift-evolution at swift.org> wrote:
> The use-case for this comes first from proposals to have a weak-reference version of collection types. Implementing a notification signal of some sort to weak reference-holders when the reference becomes nil would make implementing those more straightforward.
How do you want this to work in the presence of threads?
One option is that the nil transition and the callbacks are performed together, synchronously and atomically with respect to some things. The problem with this scheme is that the callback is limited in what it can do. If it does the wrong thing it will deadlock. The definition of "wrong thing" depends in part on the definition of "atomically with respect to some things". For example, if the callbacks are called atomically with respect to other weak reference writes then the callback must not store to any weak references of its own.
Another option is that the callbacks are performed asynchronously some time after the nil transition itself. (Java's PhantomReference offers something like this.) The problem with this scheme is that the state of the world has moved on by the time the callback is called, which can make the callback difficult to write. In particular there is no guarantee that the weak variable's storage still exists when the callback for that weak variable is executed.
Greg Parker gparker at apple.com Runtime Wrangler
More information about the swift-evolution