Executing operations in parallel while storing in order, incremental output

I have a slow processor intensive work: doWork(int x)which is called with one integer parameter with different values:

static String doWork(int x) {
  // do work that depends on i, takes ~60 seconds
  ...
}

public static void main(String args[]) {
  for (int i = 1; i < 100; i++) {
    System.println(doWork(i));
  }
}

As each call completes, the doWork()result is output to the console. I would like to parallelize this - all calls doWork()are independent and do not mutate any general state. Now I can do it the old way, mess with ExecutorSevice, Future.get()etc., but I would like to do it more cleanly with threads 1 .

So something like this looks like it could almost work:

public static void main(String args[]) {
    IntStream.rangeClosed(1, 100).parallel()
        .forEach(i -> System.out.println(doWork(i)));
}

... , ( doWork(1) ) ..). forEachOrdered(), : . , forEachOrdered : . , , .

, , idiom map -> collect, doWork() :

public static void main(String[] args) {
    System.out.println(IntStream.rangeClosed(1, 100).parallel()
        .mapToObj(Main::doWork).collect(Collectors.joining("\n")));
}

! collect() , . , - . , .

, - , . , , " " , , , .

- ? -, Collector, , .


1... , , , fork/join , , , , ?

+4
2

. map forEachOrdered:

IntStream.rangeClosed(1, 100)
         .parallel()
         .mapToObj(Main::doWork)
         .forEachOrdered(System.out::println);
+6

FWIW, , , shmosel , " FIFO" - , :

IntStream.rangeClosed(1, 100)
    .mapToObj(i -> CompletableFuture.supplyAsync(() -> doWork(i)))
    .collect(Collectors.toList())
    .forEach(f -> System.out.println(f.join()));

, , ( , parallel). collect() ( ) , ( forEach) Future, .

FIFO ( , , 3 , 3 , , , ). , , , , , 3 .

+2

Source: https://habr.com/ru/post/1663896/


All Articles