zjffdu
zjffdu

Reputation: 28944

How to kill a java thread?

I google the solution for killing a java thread. And there exists two solutions:

  1. set a flag
  2. using Thread.interrupt

But both of them are not suitable for me. In my thread, I call a third-party api which takes a long time to complete. and I want to let the user to cancel this thread if it takes too much time.

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

Upvotes: 4

Views: 15868

Answers (8)

user454322
user454322

Reputation: 7659

I would put the call a third-party api which takes a long time into a Callable<DataTypeReturnedBy3rdPartAPI> and then execute it with a SingleThreadExecutor specifying a timeout.

Following this approach, the thread will be killed if the call to third party API takes longer than timeOut, here is some code to exemplify what I am 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
  }
}; 

Upvotes: 2

Yann Ramin
Yann Ramin

Reputation: 33197

Thread.interrupt() is the only safe method which is generally applicable. You can of course use other application-level signals (such as a conditional check on a volatile variable) to self-terminate. Other methods (such as all the deprecated Thread.xx methods) can pollute your application's state in non-deterministic ways, and would require reloading all application state.

Upvotes: 5

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17445

Since Thread.stop() is (rightly) deprecated, generally this is accomplished by setting a flag to true. Something like this:

Calling Class:

...
workListExecutor.stop()
...

WorkListExecutor.class:

boolean running = true;

void stop(){
  running = false;
}

void run(){
  while (running) {
    ... do my stuff ...
  }
}

This is assuming your thread has some kind of main loop (usually the case). If the code in your loop is too big, you can periodically check if running is still true, and bail out if it's not.

This has the advantage that you can still clean up when you're done. The thread will be killed automatically when your run method finishes.

Upvotes: 0

Mike Lue
Mike Lue

Reputation: 839

In java.util.concurrent.FutureTask, the mechanism of cancellation by timeout is acted as throwing java.util.concurrent.TimeoutException.

You may check out this as if there are something to be interrupted automatically by timeout.

Upvotes: 0

verisimilidude
verisimilidude

Reputation: 736

Spawn a separate process and kill it using OS facilities. You'll have to call into "C" to do it but it won't be much code. You didn't say what OS you are running on.

Upvotes: 1

Stephen C
Stephen C

Reputation: 719446

In theory, you could call the deprecated Thread.stop() method. But beware that this could result in your application behaving in unexpected and unpredictable ways ... depending on what the third party library is actually doing. Thread.stop() and friends are fundamentally unsafe.

The best solution is to modify the 3rd-party library to respond to Thread.interrupt. If you cannot, then ditch it and find / use a better library.

Upvotes: 3

sasuke
sasuke

Reputation: 6759

You can invoke the stop method on the Thread object but it is strongly recommended that you don't. 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 CPU bound or IO bound? If it is IO bound and if you have access to the underlying socket/remote communication object, closing that object can do wonders. It is at least better than stopping the thread.

Upvotes: 0

vanza
vanza

Reputation: 9903

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

Upvotes: 0

Related Questions