views:

568

answers:

4

I have a MATLAB class which contains a reference to a java object

classdef MyClass
  properties
    j = myJavaClass
  end
  methods
...
  end
end

and after I use it (using clear, scope exit or explicitly setting myClass = 0; ) the java object is still alive - even after calling Runtime.gc.

I see in the dump that the object is still in the JVM heap for the MATLAB process (using jmap -histo pID) and thus I assume MATLAB itself is still referencing the object - despite calling to clear, clear JAVA, clear classes, etc. - nothing helps

Any ideas?

A: 

I'm not sure if this will fix it, but try making the assignment in the constructor, not in the properties block. Also, it could be helpful to mention the exact Matlab version you're using.

Mr Fooz
+1  A: 

The newest object-oriented programming format for MATLAB is still something I haven't jumped into with both feet yet, but I can try and give you a few ideas...

I'm guessing you are creating a "value class" as opposed to a "handle class" (You can check out more about these here). When copies of value classes are made, all the contents are copied. If you have an errant copy of the object floating around somewhere, then there is still a handle to the Java object in existence.

If you were to build your class off of the handle class instead, you could explicitly destroy the Java object within the class destructor (i.e. the overloaded DELETE method).

Just a couple random ideas. Hope they are helpful.

gnovice
A: 

Try taking a look at the onCleanup aspect of the OOP. I think that Loren did a blog on it about 3 months ago.

HTH. Dan

Dan
+1  A: 

The workaround gnovice suggested seem to work - adding to the destructor the line

function delete( obj )
  ...
  jObject = 0;
end

Caused the object not to be present in MATLAB's JVM heap.


It look like a bug in MATLAB that causes the referencing of the JAVA objects in unreferenced MCOS classes.

Dani