Created
November 12, 2014 05:48
-
-
Save jimexist/5adcb4575f04c8420731 to your computer and use it in GitHub Desktop.
InterruptThreadPools.java
This file contains hidden or 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.ArrayList; | |
| import java.util.List; | |
| import java.util.concurrent.*; | |
| public class InterruptThreadPools<V> { | |
| private final ExecutorService threadPool = Executors.newCachedThreadPool(); | |
| private final CompletionService<V> completionService = new ExecutorCompletionService<>(threadPool); | |
| private final BlockingQueue<Future<V>> tasks = new LinkedBlockingQueue<>(); | |
| public void submitNewTask() { | |
| tasks.add(completionService.submit(new Callable<V>() { | |
| @Override | |
| public V call() throws Exception { | |
| try { | |
| Thread.sleep(100_000_000L); | |
| return null; | |
| } catch (InterruptedException e) { | |
| System.err.println("interrupted"); | |
| Thread.currentThread().interrupt(); | |
| throw e; // unreachable | |
| } | |
| } | |
| })); | |
| } | |
| public V getResult() throws Exception { | |
| return completionService.poll(1, TimeUnit.SECONDS).get(); | |
| } | |
| public void resetAll() throws Exception { | |
| List<Future<V>> ts = new ArrayList<>(); | |
| tasks.drainTo(ts); | |
| for (Future<V> future : ts) { | |
| future.cancel(true); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment