Future.cancel () method does not work

The code I created creates an instance of Callable, and using the ExecutorService a new thread is created. I want to kill this thread after a certain amount of time if the thread is not executed with its execution. After going through the jdk documentation, I realized that the Future.cancel () method can be used to stop the flow from executing, but, unfortunately, it does not work. Of course, the future.get () method sends an interrupt to Thread after the set time (in my case, it is 2 seconds), and even the thread receives this interrupt, but this interrupt only happens after the thread is fully executed. But I want to kill the stream in 2 seconds.

Can anyone help me achieve this.

Testclass Code:

==================================== public class TestExecService { public static void main(String[] args) { //checkFixedThreadPool(); checkCallablePool(); } private static void checkCallablePool() { PrintCallableTask task1 = new PrintCallableTask("thread1"); ExecutorService threadExecutor = Executors.newFixedThreadPool(1); Future<String> future = threadExecutor.submit(task1); try { System.out.println("Started.."); System.out.println("Return VAL from thread ===>>>>>" + future.get(2, TimeUnit.SECONDS)); System.out.println("Finished!"); } catch (InterruptedException e) { System.out.println("Thread got Interrupted Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>"); //e.printStackTrace(); } catch (ExecutionException e) { System.out.println("Thread got Execution Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>"); } catch (TimeoutException e) { System.out.println("Thread got TimedOut Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>"); future.cancel(true); } threadExecutor.shutdownNow(); } } 

Class code called:

 =================================================================== package com.test; import java.util.concurrent.Callable; public class PrintCallableTask implements Callable<String> { private int sleepTime; private String threadName; public PrintCallableTask(String name) { threadName = name; sleepTime = 100000; } @Override public String call() throws Exception { try { System.out.printf("%s going to sleep for %d milliseconds.\n", threadName, sleepTime); int i = 0; while (i < 100000) { System.out.println(i++); } Thread.sleep(sleepTime); // put thread to sleep System.out.printf("%s is in middle of execution \n", threadName); } catch (InterruptedException exception) { exception.printStackTrace(); } System.out.printf("%s done sleeping\n", threadName); return "success"; } } 
+4
source share
2 answers

Your code is doing everything right. The only problem is that you are not checking Thread.isInterrupted in the while . The only way to get the message is to get to the blocking call to Thread.sleep , which will immediately throw an InterruptedException . If the cycle is long, it may take some time. That is why your code is not responding a bit.

Check the interrupt status, say, every 10,000 iterations:

 while (i < 100000) { if (i % 10000 == 0 && Thread.currentThread().isInterrupted()) return "fail"; System.out.println(i++); } 

InterruptedException is for long-running blocking methods. Thread.isInterrupted for everything else.

+7
source

cancel() simply calls interrupt() on an already executing thread.

http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html :

An interrupt is an indication of a thread that it should stop what it is doing and is doing something else. It is the programmerโ€™s decision to decide how the thread responds to an interrupt, but it is very common to terminate the thread.

An interrupted thread will throw an InterruptedException

when a thread waits, sleeps or otherwise stops for a long time and another thread interrupts it using the interrupt () method in the class Thread.

Thus, you need to explicitly make the job code when the thread is executing with information about a possible interrupt.

See also. Who calls the Java Thread () interrupt method, if I donโ€™t? .

See also How to undo the future of Java 8? since java futures only matured in Java 8.

+3
source

All Articles