Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class SleepingCallable implements Callable<String> {
- final String name;
- final long period;
- SleepingCallable(final String name, final long period) {
- this.name = name;
- this.period = period;
- }
- public String call() {
- try {
- Thread.sleep(period);
- } catch (InterruptedException ex) { }
- return name;
- }
- }
- final ExecutorService pool = Executors.newFixedThreadPool(2);
- final List<? extends Callable<String>> callables = Arrays.asList(
- new SleepingCallable("quick", 500),
- new SleepingCallable("slow", 5000));
- try {
- for (final Future<String> future : pool.invokeAll(callables)) {
- System.out.println(future.get());
- }
- } catch (ExecutionException | InterruptedException ex) { }
- pool.shutdown();
- C:devscrap>java CompletionExample
- ... after 5 s ...
- quick
- slow
- final ExecutorService pool = Executors.newFixedThreadPool(2);
- final CompletionService<String> service = new ExecutorCompletionService<String>(pool);
- final List<? extends Callable<String>> callables = Arrays.asList(
- new SleepingCallable("slow", 5000),
- new SleepingCallable("quick", 500));
- for (final Callable<String> callable : callables) {
- service.submit(callable);
- }
- pool.shutdown();
- try {
- while (!pool.isTerminated()) {
- final Future<String> future = service.take();
- System.out.println(future.get());
- }
- } catch (ExecutionException | InterruptedException ex) { }
- C:devscrap>java CompletionExample
- ... after 500 ms ...
- quick
- ... after 5 s ...
- slow
- // this waits until _all_ of the jobs complete
- List<Future<Object>> futures = threadPool.invokeAll(...);
- ExecutorService threadPool = Executors.newFixedThreadPool(2);
- ExecutorCompletionService<Result> compService
- = new ExecutorCompletionService<Result>(threadPool);
- for (MyJob job : jobs) {
- compService.submit(job);
- }
- // shutdown the pool but the jobs submitted continue to run
- threadPool.shutdown();
- while (!threadPool.isTerminated()) {
- // the take() blocks until any of the jobs complete
- // this joins with the jobs in the order they _finish_
- Future<Result> future = compService.take();
- // this get() won't block
- Result result = future.get();
- // you can then put the result in some other thread pool or something
- // to immediately start processing it
- someOtherThreadPool.submit(new SomeNewJob(result));
- }
Add Comment
Please, Sign In to add comment