Skip to content

Instantly share code, notes, and snippets.

@kasramp
Created October 9, 2018 21:47
Show Gist options
  • Save kasramp/a0571f63c0671f95f2480f1b44135f81 to your computer and use it in GitHub Desktop.
Save kasramp/a0571f63c0671f95f2480f1b44135f81 to your computer and use it in GitHub Desktop.
ExecutorService with Callable Timeout
import java.util.concurrent.*;
public class Service {
private final ExecutorService executorService;
public Service() {
executorService = Executors.newSingleThreadExecutor();
}
public void testExecutorServiceInterrputCallable() {
setTimeout(executorService.submit(() -> someBlockingTask()), 1);
System.out.println("Continue main thread!");
shutdownExecutorService();
}
private void setTimeout(Future<?> futureTask, int timeoutInSeconds) {
try {
futureTask.get(timeoutInSeconds, TimeUnit.SECONDS); // 1
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
} catch (TimeoutException timeoutException) {
futureTask.cancel(true); // 2
}
}
private void someBlockingTask() {
for(long i=0; i<=10000000;i++) {
System.out.println(i);
if(Thread.currentThread().isInterrupted()) { // 3
System.out.println("The callable has been interrupted!");
return;
}
}
}
private void shutdownExecutorService() {
executorService.shutdown();
if(!executorService.isShutdown()) {
executorService.shutdownNow();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment