Weak References as Object Accessors



September 26, 2008
URL:http://www.drdobbs.com/parallel/weak-references-as-object-accessors/210604244

Sergey Babkin is a senior developer for Aleri. He can be contacted at [email protected].


Complex multi-threaded programs often end up a tangle of interconnected objects or threads. If some parts need to be stopped (such as when a user disconnects), things become complicated. Even the orderly stopping of the entire application becomes difficult: Objects keep referencing other objects that don't exist anymore. That's why you sometimes see programs that crash on an attempt to exit.

Java programmers are bound to chime in at this point and say: "Java programs don't crash!" Right. They just throw the unhandled exceptions.

The issue usually lies in the circular connections: Two objects, each with its thread, are referencing each other. If you try to destroy one, another one might reference it and blow up. It's not always that symmetrical, but that's the gist of the problem.

But Java programmers will likely chime in again and say: "The garbage collection takes care of it!" For one thing, the garbage collection means that there are no proper destructors. The finalize() methods may get delayed for an unknown length of time, until the garbage collector decides to do its sweep. Which is not good for the expensive resources like file descriptors. They still have to be freed manually. For another thing, one object's finalize method would find another object already finalized, and might not like it. So even though things are simpler, careful consideration is still needed, and the approach I present in this article might come in useful.

Java has another useful concept -- weak references. A weak reference refers to an object but doesn't prevent this object from being garbage collected if all the normal strong references to it are gone and the system starts running short of memory. If that has happened, the weak reference would contain null. Copying a weak reference to a strong one works as an atomic act of getting a hold on the object. Deleting the strong reference releases the hold.

Consider a small practical example of a system. Consisting of the following objects, each with its own thread: