简体   繁体   中英

Why this Future's method is blocking main thread?

ExecutorService executor = Executors.newFixedThreadPool(2);

Future<Integer> calculate(Integer input) {
    return executor.submit(() -> {
        Thread.sleep(3000);
        return input * input;
    });
}

public static void main(String []args) throws Exception {
    Main m = new Main();
    System.out.println(m.calculate(5).get());
    System.out.println("Main");

We submit Callable to Executor with 2 threads, but when i tell m.calculate(5).get() it block main thread. So, I can't understand, when and why should I use Future if it blocks the main thread and doesn't run asynchronously?

If you look into the documentation of Future::get it says: " Waits if necessary for the computation to complete, and then retrieves its result. " By calling this method you agree to wait for the result in the main thread.

You can check if Future has completed by calling Future::isDone , which returns boolean.

In your scenario it can be used like this

public static void main(String []args) throws Exception {
    Main m = new Main();
    Future<Integer> futureInt = m.calculate(5);
    // do some other asynchronous task or something in main thread while futureInt is doing its calculations
    // and then call Future::get
    int result = futureInt.get();

See: doc

Future is indeed a very limited abstraction, in more realistic cases you should use CompletableFuture instead. Future is a pretty old class (since java 1.5 I guess) so the understanding of the industry has gradually evolved in the field of concurrent programming,

Nevertheless, it can still be useful by itself.

What if instead of spawning one future and immediately calling get on it, we would like to spawn many tasks and store the result in some list:

List<Future<Integer>> futures = new ArrayList<>(10);
for(int i = 0 ; i< 10; i++) {
   futures.add(calculate(<some_integer>));
}
// at this point all futures are running concurrently
for(int i = 0 ; i < 10; i++) {
   futures.get(i).get(); // will either return immediately or we'll block the main thread but the point is that all the calculations will run concurrently
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM