sam_k
sam_k

Reputation: 6023

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 this JNI function execution on some conditions if its going on, otherwise not.

new Thread(new Runnable() {
    @Override
    public void run() {
         // My jni function call, It calls my JNI layer C function.
         }
   }

Now when this thread execution is started and its doing work at JNI level I have no worries about that, but from other class or methods on some condition I want to stop this JNI work so how can I stop this thread.

Note: Here my thread also has no while-loop so I cant check with some global flag variable also.

So does anyone have an idea on how to kill a thread while its call any JNI function without while loop.

Upvotes: 5

Views: 4849

Answers (3)

Pavel Zdenek
Pavel Zdenek

Reputation: 7293

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.

Upvotes: 13

Mr.Me
Mr.Me

Reputation: 9286

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()

Upvotes: -3

vikesh
vikesh

Reputation: 31

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.

Upvotes: 2

Related Questions