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