My problem is the following; I have a class that uses non-static native methods for communicating over a serial port
public class Serial{
final static int NOT_INITIALIZED = 0;
final static int INITIALIZED = 1;
private int instanceId;
private String errorString;
private native int initPort(String port);
private native int termPort(int instanceId);
private native int getState(int instanceId);
private native int readPort(int instanceId);
private native int writePort(int instanceId);
/*... publically accessible methods follow */
}
Thus multiple classes can be instantiated, each with a specific serial port. The reason why I’m doing it this way is that it allows you to set the “errorString” field from the JNI code (when an error occurs) for the instance that called the JNI code.
I have learned that multiple instances on the same JVM will share the same JNI dll. So any global variables defined in the dll will be shared by multiple instances. For this reason communication handles and state variables are stored in an global array of structures. When initPort() is called, the instanceId field is set to an array index that contains the port handle and state (INITIALIZED or NOT_INITIALIZED).
What I do not understand is how the dll functions are shared by multiple instances. Do they each get their own copy of the function, or will calling the same function simultaneously cause errors?
There is one copy of each function. Each call occurs with a separate stack containing local variables etc.
Your functions may be thread-safe or not thread-safe. If not thread-safe, calling even different methods simultaneously from multiple threads may be harmful. You know they access global variables, but don’t mention whether you know of any synchronization. Look for documentation stating that the class and its methods are intended to be thread-safe.