Skip to content

Instantly share code, notes, and snippets.

@americanstone
Last active January 16, 2018 21:15
Show Gist options
  • Save americanstone/8fd3c47668a46f5b8cab6bd364daf5c7 to your computer and use it in GitHub Desktop.
Save americanstone/8fd3c47668a46f5b8cab6bd364daf5c7 to your computer and use it in GitHub Desktop.
CommonPoolCompletionService whenComplete hook vs ExecutorCompletionService done hook
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class CommonPoolCompletionService<V> {
private final BlockingQueue<V> completionQueue;
private final BlockingQueue<CompletableFuture<V>> completionQueue1;
public CommonPoolCompletionService() {
this.completionQueue = new LinkedBlockingQueue<>();
this.completionQueue1 = new LinkedBlockingQueue<>();
}
public CompletableFuture<V> submit(AsyncCallable<V> asyncTask) {
CompletableFuture<V> future = CompletableFuture.supplyAsync(() -> {
try {
return asyncTask.asyncCall();
} catch(InterruptedException e) {
e.printStackTrace();
return null;
}
});
future.whenComplete((r , e) -> {
completionQueue.add(r);
completionQueue1.add(future);
});
return future;
}
public V take() throws InterruptedException {
return completionQueue.take();
}
public V poll() {
return completionQueue.poll();
}
public V poll(long timeout, TimeUnit unit) throws InterruptedException {
return completionQueue.poll(timeout, unit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment