2

Below is a sample program. If i uncomment the Thread.sleep it works fine. But there may be some need, where we are not sure how much time the code written inside Call method takes, can be a infinite time. Or, can be a bad program where the DB connection logic inside Call method takes more time and we need to kill.

Could you please tell, why the below code does not work if i comment the thread.sleep and how to kill and stop that without writing Thread.interrupted condition. (Assume i do not have permission write any logic inside the Call method)

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class stopThreadTest {

    public static void main(String[] args) {

        java.util.concurrent.ExecutorService executor = null;
        Future a1 = null;

        try {
            executor = java.util.concurrent.Executors.newFixedThreadPool(4);
            a1 = executor.submit(new java.util.concurrent.Callable() {
                public String call() throws Exception {
                    int i = 0;
                    while (true) {
                        //Thread.sleep(100);
                        // System.out.println("hello");
                        if (i > 10)
                            break;
                    }
                    return null;
                }
            });

            // Wait until all threads are finish
            /*
             * while (!executor.isTerminated()) { }
             */
            System.out.println("Calling PartialOrFullSuccessCheck");

            try {
                boolean isThreadError = (a1 != null) ? ((a1.get(2,
                        TimeUnit.SECONDS) == null) ? false : true) : false;

            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);

                System.out.println("encountered problem while doing some work");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);
            }

        } finally {
            System.out.println("ShutDown Executor");
            executor.shutdown();
        }
    }
}
John Watts
  • 8,717
  • 1
  • 31
  • 35
Sarada
  • 135
  • 1
  • 7
  • I get the exact same output whether `Thread.sleep` is commented out or not. – assylias Jun 01 '12 at 15:47
  • Hi Assylias, the output is same, but the thread is not getting killed if you comment the Thread.sleep (as given here). You can verify the same using "ps -ef | grep java" in Linux or task manager in Widnows. you can see there is a process running in javaw.exe name. – Sarada Jun 02 '12 at 17:58
  • Ok I misunderstood your question. As John Watts mentioned, thread interrupting is a collaborative process in Java - so if the thread you want to kill does not bother taking your request into account it is going to be difficult. To be interruptible, a task has to be designed in a certain way. – assylias Jun 02 '12 at 21:24

1 Answers1

2

There is no safe way to stop a thread without its cooperation. Threads allow other threads to stop them by being interrupted, by periodically checking the value of some shared variable or both. Other than that, the only safe thing to do is shut down the JVM (the whole process). This post is quite detailed:

How do you kill a thread in Java?

Community
  • 1
  • 1
John Watts
  • 8,717
  • 1
  • 31
  • 35
  • Hi John, The main aim is here, there is some third party customr's API which i am going to invoke inside a thread as shown in the code, i will be calling 3rd party's API method inside Call method of Collable. I want to give some time out for execution of that 3rd parrty API method. Lets take the scenraio, where the 3rd party API has an infinite loop, and since timeout is over, how can i kill the execution of that 3rd party method. Future.Cancel does not work in a infinite loop. – Sarada Jun 02 '12 at 17:56
  • 1
    Again, I'm afraid it is not possible to stop an infinite loop in a 3rd party library like this. There used to be an API to do this called Thread.stop. It was deprecated because it is unsafe. Please read http://docs.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html for more details. – John Watts Jun 02 '12 at 18:46
  • @John Watts -- broken link. (Thanks Oracle :P ) – Jason S Feb 08 '17 at 16:16
  • Latest is at https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html – John Watts Feb 08 '17 at 20:09