Weak Objects and References

From Apache OpenOffice Wiki
Jump to: navigation, search

A strategy to avoid cyclic references is to use weak references. Having a weak reference to an object means that you can reestablish a hard reference to the object again if the object still exists, and there is another hard reference to it.

In the cyclic reference shown in the illustration Cyclic Reference, object B could be specified to hold a hard reference on object A, but object A only keeps a weak reference to B. If object A needs to invoke a method on B, it temporarily tries to make the reference hard. If this succeeds, it invokes the method and releases the hard reference afterwards.

To be able to create a weak reference on an object, the object needs to support it explicitly by exporting the com.sun.star.uno.XWeak interface. The illustration Object C calls dispose() on XComponent of Object B, depicts the UNO mechanism for weak references.

When an object is assigned to a weak reference, the weak reference calls queryAdapter() at the original object and adds itself (with the com.sun.star.uno.XReference interface) as reference to the adapter.

The UNO weak reference mechanism

When a hard reference is established from the weak reference, it calls the queryAdapted() method at the com.sun.star.uno.XAdapter interface of the adapter object. When the original object is still alive, it gets a reference for it, otherwise a null reference is returned.

The adapter notifies the destruction of the original object to all weak references which breaks the cyclic reference between the adapter and weak reference.

Writing UNO Components describes the helper classes in C++ and Java that implement a Xweak interface and a weak reference.

Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages