Main Content

Weak Reference Handles

Since R2024b

A weak reference to a handle object works much like a regular handle, but a weak reference does not prevent the object it references from being deleted. You can use weak references to manage object lifecycles more efficiently.

Create Weak References

For example, this class defines a property using the WeakHandle property attribute. (See Property Attributes for more information.)

classdef Example < handle
    properties (WeakHandle)
        Prop Example
    end
end

Create two instances of the class, and use the second instance as the value of Prop in the first.

x = Example;
y = Example;
x.Prop = y;

The second instance of Example is referenced by two handles: y and x.Prop, and x.Prop is a weak reference. Clear y.

clear("y");

If x.Prop were a strong reference, the object it referenced would still exist. However, x.Prop is a weak reference, so MATLAB® deletes the object. Verify this by accessing x.Prop.

x.Prop
ans = 

  handle to deleted Example

Outside of the context of a property definition, you can also create weak references using the matlab.lang.WeakReference wrapper class. See matlab.lang.WeakReference for an example.

Create Back Pointers Using Properties Defined with WeakHandle Attribute

Data structures like trees or lists can contain objects with back pointers to objects above them in a hierarchy. Back pointers that are strong reference handles force MATLAB to do extra work when checking to see which objects can be deleted. Replacing strong references with weak references provides more efficient management of handle objects.

For example, the class Car contains properties that reference parts of a car. The class Engine represents one part that Car can reference.

classdef Car < handle
    properties
        VIN string
        EngineInstalled Engine
    end
end
classdef Engine < handle
    properties (WeakHandle)
        InstalledIn Car
    end
    properties
        SerialNumber string = "00000"
        LastService datetime = "today"
    end
end

The Engine class defines a weak reference, InstalledIn, back to the car that the engine is installed in. All properties defined with the WeakHandle attribute must use class validation. In this case, InstalledIn must be of type Car.

Construct myCar and myCarEngine. Assign myCarEngine to the EngineInstalled property of myCar, and set the InstalledIn property of myCarEngine to myCar.

myCar = Car;
myCarEngine = Engine;
myCar.EngineInstalled = myCarEngine;
myCarEngine.InstalledIn = myCar;

Now, both myCar and myCarEngine reference each other, although the reference from myCarEngine to myCar is a weak reference. Clear myCar.

clear("myCar")

If the handle in the InstalledIn property of myCarEngine were a strong reference, the object pointed to by myCar would still exist because it would be strongly referenced by myCarEngine.InstalledIn. However, the myCarEngine.InstalledIn property is now the only reference to myCar. Because myCarEngine.InstalledIn is a weak reference, it does not prevent MATLAB from deleting the myCar object. Confirm this by accessing myCarEngine.InstalledIn.

myCarEngine.InstalledIn
ans = 

  handle to deleted Car

Create a Cache Using the matlab.lang.WeakReference Class

You can use weak references to design a cache. Because caches are usually intended for quick access to data without necessarily preserving that data, you can use weak references to help manage lifecycles of data objects. Each object in the cache can have a weak reference, but the weak references do not prevent the code that manages the cache from deleting objects.

First, define a basic class TrialData that represents experimental data.

classdef TrialData < handle
    properties
        trialNumber string = "A001"
        trialResults double = 0
    end
end

Create the basis for a cache by defining a dictionary, workingData. The dictionary maps a string-valued key to a weak reference to the data object. You cannot use the WeakHandle property attribute here, so instead use an empty array of the matlab.lang.WeakReference wrapper class as the initial value.

workingData = dictionary(string.empty,matlab.lang.WeakReference.empty)
workingData =

  dictionary (string ⟼ matlab.lang.WeakReference) with no entries.

Construct two instances of TrialData and add them to workingData. Use the trialNumber property of the TrialData instances as the keys for the entries in the dictionary. The dictionary values are weak references to first and second because the dictionary values were initially defined as type matlab.lang.WeakReference.

first = TrialData;
second = TrialData;
second.trialNumber = "A002";
second.trialResults = 1;
workingData(first.trialNumber) = first;
workingData(second.trialNumber) = second
workingData =

  dictionary (string ⟼ matlab.lang.WeakReference) with 2 entries:

    "A001" ⟼ 1×1 matlab.lang.WeakReference
    "A002" ⟼ 1×1 matlab.lang.WeakReference

The instance referenced by each dictionary value is held by the Handle property of matlab.lang.WeakReference. Access the property values of the object referenced by “A002” through the Handle property.

result2 = workingData("A002").Handle.trialResults
result2 =

     1

Because the dictionary values are weak references, they do not prevent any of the objects referenced from being cleared from memory. Clear second, and confirm that the reference in the dictionary now points to a deleted object.

clear("second")
workingData("A002").Handle
ans = 

  handle to deleted TrialData

Immediate Destruction of Weak References

MATLAB immediately deletes an object that has only weak references to it. For example, construct an instance of Example from the introduction to Create Weak References. Set Prop using the Example constructor instead of creating a separate instance as a strong reference.

classdef Example < handle
    properties (WeakHandle)
        Prop Example
    end
end
x = Example;
x.Prop = Example;

Because the object referenced by x.Prop has only a weak reference, MATLAB deletes it immediately after it is created.

x.Prop
ans = 

  handle to deleted Example

To avoid this behavior, define a strong reference first so that MATLAB does not immediately delete the object, as shown in the Create Back Pointers Using Properties Defined with WeakHandle Attribute example.

See Also

| |

Related Topics