I have a certain process which can be execute in a Thread. I need to stop the processing completely after certain time Example :90 seconds.
I read we have an option in futuretask to set the timeout for a thread. But i am getting the timeout exception but the started task is running in the backend, it is not completely stopped on using futureTask.cancel(true)
or executor.isShutdown()
.
I tried to split it up and test how to stop the thread completely , but even I could not stop the started thread completely, Below the sample piece of code. Using below code the callable is not returning the String after we cancel the thread, but i could see the for is not stopping on cancelling the thread.
Please help me where it is missed?
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureTaskDemo {
public static void main(String... args) throws InterruptedException, ExecutionException{
ExecutorService exService = Executors.newSingleThreadExecutor();
FutureTask<String> futureTask= new FutureTask<String>(new Task());
exService.execute(futureTask);
//checks if task done
System.out.println("Task Done :"+futureTask.isDone());
//checks if task canceled
System.out.println("Task isCancelled :"+futureTask.isCancelled());
boolean isCancel = futureTask.cancel(true);
System.out.println("Cancelled :"+isCancel);
//fetches result and waits if not ready
System.out.println("Task is done : "+futureTask.get());
}
}
class Task implements Callable<String>{
public String call() {
for (int i=0; i<10000; i++){
System.out.println(i);
}
return "Task Done";
}
}