Stop Java thread that calls JNI function

Here I want to stop a thread or kill my thread that is being created in the Java layer and that thread is calling a JNI function. Sometimes, according to the requirements of my application, I have to stop the execution of the JNI function under certain conditions if this happens, 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 work at the JNI level, I do not worry about it, but from another class or methods under some conditions, I want to stop this JNI work in order to stop this thread.

Note: Here my thread also doesn't have a while loop, so I can't check with some global flag variable either.

Does anyone have an idea on how to kill the thread while it is calling some JNI function without a while loop.

+3


source to share


3 answers


You cannot safely interrupt a thread if it is executing native code. Even if there was an event loop in your thread, you need to wait until it completes its own call. Without knowing about your code, I would assume you had a long working call, you didn't want it to clog the main thread, so you created a separate thread for that call. You cannot safely interrupt one own call. There is no silver bullet here. You should change your code anyway, my suggestions:

  • decompose your single long native call into a series of short calls and start an event loop on the Java side.
  • decompose the inner call on the inner side and start the event loop on its own side. Your native interface will need a different method to set the interrupt flag.


Thread.interrupt()

won't help you because "calling your own function" is not subject to any of the interrupts specified in the Javadoc. The Java thread will continue to run, only the interrupt status will be set.

+9


source


Better not to kill the thread cool. Resources allocated by the C function cannot be released.



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

+2


source


There is nothing special about this code being native "Called via JNI" or pure Java, all I / O codes use JNI code, and you can stop it using normal Java Thread methods.

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

-2


source







All Articles