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();
}
}
}