与CompletableFuture
可能的解决方案:
class Job<T> {
private final Supplier<T> computation;
private final CompletableFuture<T> future;
Job(Supplier<T> computation, CompletableFuture<T> future) {
this.future = future;
this.computation = computation;
}
public Supplier<T> getComputation() {
return computation;
}
public CompletableFuture<T> getFuture() {
return future;
}
}
public void client() {
// on the client:
CompletableFuture<String> future = new CompletableFuture<>();
Supplier<String> computation =() -> "Here I am!";
enqueue(new Job<>(computation, future));
String resultString = future.get();
}
public <T> void server(Job<T> job) {
// on the server; job is taken from the queue
CompletableFuture<T> future = job.getFuture();
future.complete(job.getComputation().get());
}
在这里,在客户端上,future.get()
会无限等待,直到结果可用。还有另一种形式:
future.get(1, TimeUnit.MINUTES)
只会等待一分钟然后返回。这可以用于轮询。
为什么不把期货添加到您现有的架构中?传递'CompletableFuture'而不是该轮询相关的结构。然后可以使用'get()'方法通过静音等待(或者轮询)。 –
@RomanPuchkovskiy我想我不知道从哪里开始实施未来的机制。也许我想得太过分了.....除非我有一个聪明的想法,简单地使用信号量作为get方法的一种等待锁:/ –
为建议的方法增加了一个插图 –