Java 8 Concurrency Simplest Canonical Form for Basic Task

Viewed 123

I have two questions: 1. What is the simplest canonical form for running a Callable as a task in Java 8, capturing and processing the result? 2. In the example below, what is the best/simplest/clearest way to hold the main process open until all the tasks have completed?

Here's the example I have so far -- is this the best approach in Java 8 or is there something more basic?

import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;

public class SimpleTask implements Supplier<String> {
  private SplittableRandom rand = new SplittableRandom();
  final int id;
  SimpleTask(int id) { this.id = id; }
  @Override
  public String get() {
    try {
      TimeUnit.MILLISECONDS.sleep(rand.nextInt(50, 300));
    } catch(InterruptedException e) {
      System.err.println("Interrupted");
    }
    return "Completed " + id + " on " +
      Thread.currentThread().getName();
  }
  public static void main(String[] args) throws Exception {
    for(int i = 0; i < 10; i++)
      CompletableFuture.supplyAsync(new SimpleTask(i))
        .thenAccept(System.out::println);
    System.in.read(); // Or else program ends too soon
  }
}

Is there a simpler and clearer Java-8 way to do this? And how do I eliminate the System.in.read() in favor of a better approach?

2 Answers
Related