Skip to content

Instantly share code, notes, and snippets.

@jimexist
Created November 12, 2014 05:48
Show Gist options
  • Select an option

  • Save jimexist/5adcb4575f04c8420731 to your computer and use it in GitHub Desktop.

Select an option

Save jimexist/5adcb4575f04c8420731 to your computer and use it in GitHub Desktop.
InterruptThreadPools.java
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