Skip to content Skip to sidebar Skip to footer

Stop Java Thread Which Call Jni Function

Here I want to stop my thread or kill my thread which is created on Java layer, and this thread is calling JNI function. Sometimes as per my application requirement, I have to stop

Solution 1:

You can't safely interrupt a thread, if it is executing a native code. Even if your thread had an event loop, you need to wait until it finishes the native call. Knowing nothing about your code, i would guess that you had a long running native call, you didn't want it to clog the main thread, so you created a separate thread for that call. There is no way you can safely interrupt a single native call. No silver bullet here. You need to change your code in any case, my suggestions would be:

  • decompose your single long native call into series of short calls and run event loop on Java side
  • decompose the native call internally on the native side and run the event loop on native side. Your native interface will need another method for setting the interruption flag.

Thread.interrupt() won't help you because "calling native function" doesn't fall under any of the interruptible actions specified in Javadoc. The Java thread will keep running, only it's interrupt status will be set.

Solution 2:

Its best not to kill a thread abruptly. The resources allocated by the C function may not be freed.

If the C function is waiting on something, you can trigger a condition to return back and check for the error code.

Solution 3:

There is nothing special about the code being native "Called through JNI" or pure Java , All IO code use JNI code and you can stop it using ordinary Java Thread methods.

Just Use Thread.Stop() or Thread.Inturrupt()

Post a Comment for "Stop Java Thread Which Call Jni Function"