Java Stream How to - Use lambda to pass Future to ExecutorService








Question

We would like to know how to use lambda to pass Future to ExecutorService.

Answer

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
/*  www. j  ava 2s.  c om*/
public class Main {

  public static void main(String[] args) throws InterruptedException, ExecutionException {

    ExecutorService ex = Executors.newSingleThreadExecutor();


    Future<Integer> future =
            // This Lambda evaluated to Callable<Integer>
            ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10));


    System.out.println("Randomized value: " + future.get());


  }
}

The code above generates the following result.