This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: You Are a Such Weakling!
Feed Title: Travis Griggs - Blog
Feed URL: http://www.cincomsmalltalk.com/rssBlog/travis-rss.xml
Feed Description: This TAG Line is Extra
First of all, thanks much to Steve Dahl of Cincom for helping me get this figured out.
Ever had an object that has a slot (ivar) intended to point at another object that *might* be there? It might be there, because well it might be. But you don't want to be responsible for it to be kept around if other consumers of the object have all given it up. With no weakness facilities, you have a dillema. If you hold a reference to the object so you can check on it, even though all other objects have given up on it, you'll prevent the garbage collector from reclaiming the object.
Luckily in Smalltalk, we have those weakness facilities. Where you'll common see this pattern in lookup caching. I want to lookup an object associated with another object, but if the key goes away, I don't want the association keeping the lookup value around. Registry, WeakDictionary, WeakKeyDictionary, WeakKeyAssociatin, Ephemeron all play roles in this kind of usage.
What if you don't need a cache though? What if you just want that slot we were talking about? With Steve Dahl's clarification of ephemerons, I was able to put together the Weaklings package. It allows you to send asWeakling to an object and get it wrapped with a weak value/value: like thingie. There's also an ambitious weak proxy that uses DNU: to avoid the usage of value/value:. If you have something where weakness might make your application easier, give it a try! It's great for example, for a weak class side singleton.
An even more interesting problem, that it solved for me, was one where processes are involved. Let's say you have an object, which you associate a periodic loop to update it with. Even though nobody else continues to use your object, it can't be GC'd, because it can be reached through the process. But the process was supposed to be secondary, just there to update the object, as long as it was alive. Having a weakling (you can do it with a WeakArray too) is one way around this problem. In fact, I was so happy with Weakings, that I immediately switched ExtraEmphases to use them. And it solved a problem I was having with an object that was periodically polled hardware interface. The basic in this case is something like:
startPolling
me := self asWeakling.
loop :=
[| continue |
continue := true.
[continue and: [me value notNil]] whileTrue:
[(Delay forSecond: 0.1) wait.
[me value ifNotNil: [:myself | myself doUpdate]] on: Error
do:
[:ex |
ex logError.
continue := false]].
loop := nil]