In matlab, I have a class that ties up a shared resource during construction and releases it when deleted. (In my specific case, the shared resource is a port I can interact with it via http://localhost:1234)
It looks like this:
classdef myClass < handle
methods
function myClass()
OpenExecutableUsingPort1234();
end
function delete(this)
CloseExecutableUsingPort1234();
end
end
end
when I use it like this:
instance = myClass();
clear instance;
everything works fine. I open and close it without a problem. But when I use it like this:
instance = myClass();
instance = myClass(); % can't access the port during construction, because it's in use.
I can't start the executable because the port is in use.
The order of events is this:
- a first copy of myClass is constructed. there is no problem with ports
- the copy is assigned to the 'instance' variable.
- a second copy of myClass is constructed. It can't start the executable because the port is in use
- the new copy is assigned to the 'instance' variable
- the first copy no longer has any references to it, and calls its delete method. This frees up the port.
What kind of workarounds are possible?
Ideally, I'd like step 5 to just know it needs to run early:
- a first copy of myClass is constructed. there is no problem with ports
- the copy is assigned to the 'instance' variable.
5. the first copy no longer has any references to it, and calls its delete method. This frees up the port.
- a second copy of myClass is constructed. the port is free too!
- the new copy is assigned to the 'instance' variable
You have to do a manual clear if you want the old instance to go away before the new instance starts creation.
If you do this:
The second line calls the
myClassconstructor before theinstancevariable gets reassigned, triggering GC on the first instance. It doesn't changeinstanceuntil the second constructor returns, and it has a new value to put in it. (E.g. if the myClass constructor threw an error,instanceshould remain unchanged.)Just stick a clear in there:
(This behavior isn't guaranteed by the Matlab language specification as far as I can tell, but it's how things currently work.)
Example:
Behavior:
If you really wanted it to work differently, you could write your class so that there can only be one active instance. Hold on to that in a
persistentvariable in the class definition. When a new instance is created, have it blow away the actual connection in the prior instance. I think that's kinda gross, though.Or just work with a single Singleton instance of your class, and have its properties be mutable so you can alter its state instead of creating a new instance.