简体   繁体   中英

What's wrong on the following using CompletableFuture?

I am new to CompletableFuture, here is a simple one I would like to try

 CompletableFuture.supplyAsync( ()-> {System.out.println("async");});

When I try to compile, it gave the error

Error:(23, 26) java: no suitable method found for supplyAsync(()->{ Syst[...]"); })
    method java.util.concurrent.CompletableFuture.<U>supplyAsync(java.util.function.Supplier<U>) is not applicable
      (cannot infer type-variable(s) U
        (argument mismatch; bad return type in lambda expression
          missing return value))
    method java.util.concurrent.CompletableFuture.<U>supplyAsync(java.util.function.Supplier<U>,java.util.concurrent.Executor) is not applicable
      (cannot infer type-variable(s) U
        (actual and formal argument lists differ in length))

I am wondering what's wrong with the above?

Like it says in the error message:

missing return value

Suppliers have to return a value. Try:

CompletableFuture.supplyAsync(()-> {System.out.println("async"); return null;});

or, like Flown points out, use runAsync :

CompletableFuture.runAsync(()-> System.out.println("async"));

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