如何在 Java 中创造一个完整的未来

在 Java 中构建一个完整的未来的最佳方式是什么?我已经在下面实现了我自己的 CompletedFuture,但是希望类似的东西已经存在。

public class CompletedFuture<T> implements Future<T> {
private final T result;


public CompletedFuture(final T result) {
this.result = result;
}


@Override
public boolean cancel(final boolean b) {
return false;
}


@Override
public boolean isCancelled() {
return false;
}


@Override
public boolean isDone() {
return true;
}


@Override
public T get() throws InterruptedException, ExecutionException {
return this.result;
}


@Override
public T get(final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}
65305 次浏览

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

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

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

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

 Future future = CompletableFuture.completedFuture(value);

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