-
-
Save kasramp/a0571f63c0671f95f2480f1b44135f81 to your computer and use it in GitHub Desktop.
ExecutorService with Callable Timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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