While I was exploring ExecutorService, I encountered a method Future.get() which accepts the timeout.
The Java doc of this method
my callable will interrupt after the specified time(timeout) has passed
Not true. The task will continue to execute, instead you will have a null string after the timeout.
If you want to cancel it:
timeout.cancel(true) //Timeout timeout = new Timeout();
P.S. As you have it right now this interrupt will have no effect what so ever. You are not checking it in any way.
For example this code takes into account interrupts:
private static final class MyCallable implements Callable{
@Override
public String call() throws Exception {
StringBuilder builder = new StringBuilder();
try{
for(int i=0;i
And then:
ExecutorService service = Executors.newFixedThreadPool(1);
MyCallable myCallable = new MyCallable();
Future futureResult = service.submit(myCallable);
String result = null;
try{
result = futureResult.get(1000, TimeUnit.MILLISECONDS);
}catch(TimeoutException e){
System.out.println("No response after one second");
futureResult.cancel(true);
}
service.shutdown();