简体   繁体   中英

Java : How to stop a Thread that's calling a succession of C++ functions using a JNI function?

So, here is my situation :

I've got a Java application that is sending arrays of data to a C++ DLL using a JNI method from a "JavaToCpp" class.

Once the C++ DLL have received all the data, it begins performing several actions on it.

I'm running the "JavaToCpp" class using a new thread, for my Java interface not to be frozen during the (long) (C++) procedures/subroutines.

I implemented two methods to stop the working (C++) procedures/subroutines :

  • The first one "STOP" : is creating a file which is going to be read by the C++ DLL so it can cleanly stop the running procedures/subroutines.
  • The second one "KILL" : is supposed to shutdown / kill the running C++ procedures/subroutines directly

The problem is that, after looking for a while, I did not find any good trick to perfom it.

So if anyone's got an idea on how to kill a Thread while procedures/subroutines are being running ...

The best practice way is to have a volatile variable which is checked by the long running task to determine when to stop. You can use the Thread.currentThread().isInterrupted() flag.

The problem is that most thread you want to kill because they are not well behaved. In this situation your only option is to kill the process, which usually means starting it in a different process first.

The only way in to "kill" a Thread in Java is the deprecated stop() method.

Before you plan to use it, read and understand why it's deprecated . If you understand it, you won't use it.

So no, there's no good way to kill a thread. But why are you talking about C++ processes (or did you mean procedures, ie subroutines)? Because if you use a separate process (not thread) to do the native part, the you could easily stop it: use ProcessBuilder and Process.destroy() . There are other advantages too in using processes instead of threads to invoke native stuff. One benefit is that an unstable native process won't kill your Java process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM