SHARE
TWEET

ForkJoinPool.commonPool().invokeAll(...)

DulcetAirman Jun 3rd, 2019 (edited) 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin;
  2.  
  3. import java.util.List;
  4. import java.util.concurrent.*;
  5. import java.util.stream.*;
  6.  
  7. public final class SomeClass implements Callable<Integer> {
  8.  
  9.   private final int value;
  10.  
  11.   public SomeClass(int i) {
  12.     this.value = i;
  13.   }
  14.  
  15.   @Override
  16.   public Integer call() throws Exception {
  17.     System.out.println("started: " + value);
  18.     Thread.sleep((long) (1000 * Math.random()));
  19.     System.out.println("finished: " + value);
  20.     return value;
  21.   }
  22.  
  23.   public static void main(String[] args) throws InterruptedException {
  24.     // List of 10 instances of SomeClass:
  25.     List<SomeClass> tasks = IntStream.range(0, 10).mapToObj(i -> new SomeClass(i))
  26.         .collect(Collectors.toList());
  27.  
  28.     // This would work, but is sequential instead of parallel:
  29.     // tasks.stream().map(ForkJoinPool.commonPool()::submit)
  30.     // This would work, but it messes up the order:
  31.     // tasks.parallelStream().map(ForkJoinPool.commonPool()::submit)
  32.    
  33.     // Process the list and print all results in correct order:
  34.     ForkJoinPool.commonPool().invokeAll(tasks).stream()
  35.       .map(t -> {
  36.         try {
  37.           return t.get();
  38.         } catch (InterruptedException | ExecutionException e) {
  39.           // Java isn't exactly elegant when it comes to streams and exceptions
  40.           throw new RuntimeException(e);
  41.         }
  42.       }).forEach(System.out::println);
  43.  
  44.     // Not necessary, but to really make sure the tasks are all processed:
  45.     ForkJoinPool.commonPool().awaitTermination(100, TimeUnit.SECONDS);
  46.     System.out.flush();
  47.   }
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top