Different Outputs when running threads

#1

Hey guys, I’ve been writing this code to conduct async callbacks from rust to java.

Link to the code: https://github.com/Yoga07/java-jni-rust/tree/jni-error

The two threads at the last function of lib.rs are the ones implementing jni java callbacks and rust functions.

I get different outputs every time I run them. Sometimes it works as it was intended to be. Other times, it doesn’t. I am not able to understand this behavior. Eg.

OUTPUT 1:

[Rust]Hello World!
[Java] 8
[Java]hello
[Java]->Name=Lionel, Balance=100.0
[Rust]Rust is processing
Rust->Calls back to Java
[Java]Java executes callbacks

OUTPUT 2:

[Rust]Hello World!
[Java] 8
[Java]hello
[Java]->Name=Lionel, Balance=100.0
[Rust]Rust is processing

OUTPUT 3:

[Rust]Hello World!
[Java] 8
[Java]hello
[Java]->Name=Lionel, Balance=100.0
[Rust]Rust is processing
Rust->Calls back to Java
[Java]Java executes callbacks
[Rust]Rust finishes processing
Java Responds

OUTPUT 3 is the correct and expected out. Please help me clarify this behaviour. Thanks in advance! :slight_smile:

0 Likes

#2

IDK much JNI stuff but your main problem appears to me to be thread synchronisation issue (whether by using joins or synchronised shared values/memory between the threads (e.g. Arc or Arc<Mutex etc.,).

If that is the case, would it be more helpful if you wrote programs wholly in Rust (avoiding the distractions of FFI) and studied a bit about it and see if the behaviour concurs with your line of thought ? Then if it doesn’t (and once you have read enough literature by yourself on multithreading) come back here with a pure Rust e.g., that you think has a surprising behaviour and then see what others have to say.

3 Likes