How to kill java thread?

I have a google solution to destroy Java thread. And there are two solutions:

  • set flag
  • using thread.interrupt

But both of them do not suit me. In my thread, I call a third-party api, which takes a lot of time. and I want the user to be able to cancel this thread if it takes too much time.

So how can I kill this thread? Thanks in advance.

+4
source share
8 answers

Thread.interrupt() is the only safe method that is usually applicable. Of course, you can use other application-level signals (such as conditional checking of a variable) to terminate yourself. Other methods (for example, all obsolete Thread.xx methods) can pollute your application state in non-deterministic ways and require reloading the entire application state.

+5
source

In theory, you can call the deprecated Thread.stop() method. But be careful that this can cause your application to run in unpredictable and unpredictable ways ... depending on what the third-party library actually does. Thread.stop() and friends are mostly unsafe.

The best solution is to modify a third-party library to respond to Thread.interrupt. If you cannot do this, select it and find / use the best library.

+3
source

I would put a call to a third-party api, which takes a lot of time in Callable<DataTypeReturnedBy3rdPartAPI> , and then execute it with SingleThreadExecutor , specifying a timeout .

After this approach, the thread will be killed if calling a third-party API takes longer than timeOut , here is some code to demonstrate what I'm saying:

 ExecutorService executor = Executors.newSingleThreadExecutor(); try { //================= HERE ================== Future<Boolean> job = executor.submit(thirdPartyCallable); executor.awaitTermination(timeOut, TimeUnit.SECONDS); if(!job.isDone()) logger.debug("Long call to 3rd party API didn't finish"); //========================================= } catch (Exception exc) { exc.printStackTrace(); } finally { if(!executor.isShutdown() ) executor.shutdownNow(); } } private static Callable<Boolean> thirdParytCallable = new Callable<Boolean>() { public Boolean call() throws Exception { //Call to long 3rd party API //....... for(long i = 0;i<99999991999999L;i++) { Thread.sleep(10L);// Emulates long call to 3rd party API System.out.print("."); } return Boolean.valueOf(true);//Data from 3rd party API } }; 
+2
source

Create a separate process and kill it using OS objects. You will need to call "C", but that will not be very much code. You did not say which OS you are running on.

+1
source

You can try Thread.stop () , but at your own risk . Optimally, the API you are calling should have a way to abort the operation if necessary (what is Thread.interrupt () , if the API itself does not provide a cleaner way to abort its progress, have you tried?).

0
source

You can call the stop method on the Thread object, but it is highly recommended that you do not. Read this: http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

Do you have the freedom to make minor changes to the API? Is this blocking call to the CPU bound or linked to IO? If it is tied to IO, and if you have access to the base socket / remote communication object, closing this object can work wonders. This is at least better than stopping the stream.

0
source

In java.util.concurrent.FutureTask , the timeout cancellation mechanism acts like a java.util.concurrent.TimeoutException throws.

You can check this as if something was automatically interrupted by a timeout.

0
source

Since Thread.stop() (correctly) deprecated, this is usually achieved by setting the flag to true. Something like that:

Call Class:

 ... workListExecutor.stop() ... 

WorkListExecutor.class:

 boolean running = true; void stop(){ running = false; } void run(){ while (running) { ... do my stuff ... } } 

This assumes your thread has some kind of main loop (usually this is the case). If the code in your loop is too large, you can periodically check to see if running true remains, and exit if it is not.

This has the advantage that you can still clean when done. The thread will be automatically destroyed when your execution method ends.

0
source

All Articles