How to create a completed future in java

前端 未结 6 883
不思量自难忘°
不思量自难忘° 2021-02-06 20:12

What is the best way to construct a completed future in Java? I have implemented my own CompletedFuture below, but was hoping something like this that already exist

相关标签:
6条回答
  • 2021-02-06 20:31
    FutureTask<String> ft = new FutureTask<>(() -> "foo");
    ft.run();
    
    System.out.println(ft.get());
    

    will print out "foo";

    You can also have a Future that throws an exception when get() is called:

    FutureTask<String> ft = new FutureTask<>(() -> {throw new RuntimeException("exception!");});
    ft.run();
    
    0 讨论(0)
  • 2021-02-06 20:33

    I found a very similar class to yours in the Java rt.jar

    com.sun.xml.internal.ws.util.CompletedFuture

    It allows you to also specify an exception that can be thrown when get() is invoked. Just set that to null if you don't want to throw an exception.

    0 讨论(0)
  • 2021-02-06 20:34

    In Java 6 you can use the following:

    Promise<T> p = new Promise<T>();
    p.resolve(value);
    return p.getFuture();
    
    0 讨论(0)
  • 2021-02-06 20:35

    Guava defines Futures.immediateFuture(value), which does the job.

    0 讨论(0)
  • 2021-02-06 20:41

    In Java 8 you can use the built-in CompletableFuture:

     Future future = CompletableFuture.completedFuture(value);
    
    0 讨论(0)
  • 2021-02-06 20:45

    Apache Commons Lang defines similar implementation that is called ConstantFuture, you can get it by calling:

    Future<T> future = ConcurrentUtils.constantFuture(T myValue);
    
    0 讨论(0)
提交回复
热议问题