cleaning problem using java classes in matlab

956 Views Asked by At

I am writing a java application with a matlab ui. For this I use java objects in matlab as explained here: http://www.mathworks.com/help/techdoc/matlab_external/f4873.html

What I want to do is create a matlab function like this:

function [] = foo 
  o = javaObject('myObject',parameters...);
  o.memberfunction(parameters...);

I want foo to behave exactly the same as if it was a main function in java. So want everything cleaned up at the end of a run of foo, also the static class fields.

example where a problem occurs:

first run foo:
static fields are set to some values V
second run foo:
static fields are still set to values V 

I tried clearing the instance o but this did not solve anything (after a (rather long) while matlab did clean up the instance but obviously not the class fields).

2

There are 2 best solutions below

2
On

If you are using Swing, you should be able to destroy the GUI by programatically closing the main window and setting JFrame.DISPOSE_ON_CLOSE. But the purpose of static members is to persist in situations like this. What is the purpose of the statics; why aren't they instance variables of your app or main window?

1
On

The "clear java" command will probably do what you want. It will unload all the Java classes it has loaded in.

In Java, it's not exiting the main() method that causes statics to be cleaned up; it's the JVM preparing for shutdown when all non-daemon threads have exited. The main() execution is just one of those threads.

You'd probably have better luck converting them to instance variables. Or rather, taking all those statics, packaging them up in another class, and having all your instances carry a reference to a single shared object of that class.