How to create a completed future in java

余生颓废 提交于 2019-12-03 09:16:54

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

Future<T> future = ConcurrentUtils.constantFuture(T myValue);

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

 Future future = CompletableFuture.completedFuture(value);
Louis Wasserman

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

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();

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.

In Java 6 you can use the following:

Promise<T> p = new Promise<T>();
p.resolve(value);
return p.getFuture();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!