I'm having a tough problem with invoking a native function using JNI from a thread.
The native function is legacy code that performs a computation-intensive task. Since I'd like not to freeze the rest of the program, the computation should be performed in a background thread. EventBus is used to send the calculation result back to the main program.
Basically it should be quite simple, something like this:
public class CalculationEngine {
private CalculationEngine(){}
public static void calculateInBackground(final Parameters parameters) {
new Thread(new Runnable() {
public void run() {
// Someone might change the parameters while our thread is running, so:
final Parameters clonedParameters = parameters.clone();
Results results = new Results();
natCalc(clonedParameters, results);
EventBus.publish("Results", results);
}
}).start();
}
public static void calculateNormally(final Parameters parameters) {
Results results = new Results();
natCalc(parameters, results);
EventBus.publish("Results", results);
}
private static native synchronized void
natCalc(Parameters parameters, Results results);
}
Now, the calculateNormally
method, which blocks the main program, works fine, but the calculateInBackground
method, which just constructs a background thread to do the same thing, causes various crashes in the native code when it's invoked consecutively. By consecutively I mean that it's called again only after the previous thread has finished and returned the result. Note that the native code is marked synchronized
to ensure that only one instance of it can be running at a time.
My question is, how on earth can the native code behave differently depending on whether it's invoked from the main thread, or from some other thread? It's like the native code were keeping "state", and not really quitting, when it's called from within a thread other than the main thread. Is there a way to "clean" or "flush" a thread after it's finished? There must be something in JNI & Threads that I simply don't know.
Thanks for any hints!