Making Java classes Matlab friendly

Using Java classes from Matlab reveals two common bugs that should be fixed before using your Java classes from Matlab.  While both of these bugs are really due to slopy programming, they never cause errors in the default Java environment (i.e. starting a java app from the command line) so you will find them in a lot of Java classes, including those in the TinyOS Java toolset.

Command Line Arguments

Let's say that you're using a shell and you want SerialForwarder to connect to COM2 instead of COM1 and you want oscilloscope to listen for Group ID 122 instead of 125.  From your shell, you would pass command line arguments as follows:

java net/tinyos/sf/SerialForward -comm COM2
java net/tinyos/oscope/oscilliscope
122

If you want to do the same thing from the Matlab command prompt, you would use the following syntax

net.tinyos.sf.SerialForward.main({'-port','COM2'})
net.tinyos.oscope.oscilloscope.main({'122'})

This is because the command line arguments from your shell are automatically packaged up into string arrays and passed to the static main function of your class.  In Matlab you need to pass string arrays directly.  In Matlab syntax,  '...' is a string and {'...', '...', ..., '...'} is an array of strings.

Now, what if we don't want to pass any command line arguments?  We should send a null array, which in matlab would be '{ }'.  Let's try it:

net.tinyos.sf.SerialForward.main({})

We get a null pointer exception!  This is because the main function in SerialForwarder uses the string before checking if it is null.  Since sending no command-line arguments from the shell doesn't result in a null string being passed, this normally doesn't cause an error.  However, this should be fixed if this class were to be used from Matlab.

Virtual Machines

If you had used the shell commands above, notice that you would have called the "java" command twice.  This means that you have started two JVMs (Java Virtual Machines), one that is running SerialForwarder and one that is running Oscilloscope.

In Matlab, on the other hand, you instantiated both objects within the same JVM.  Furthermore, Matlab itself is also running in this same JVM.  Is this important?  Only for the java.lang.System class, which directly refers to the JVM you are running in;  java.lang.System.exit() will kill your JVM, and therefore both classes and your Matlab session!!  You will see this if you close the oscilloscope window, because this causes oscilloscope to call System.exit().  If this class were to be used from Matlab, it should be changed to first close the socket, then deregister itself from everything and release all resources (i.e. dispose the window).  System.exit( ) should never be called.