It's rather trivial, just change one of your methods:
private static CompletableFuture<String> query(Collector collector) {
return CompletableFuture.supplyAsync(() -> {
collector.collectStuff();
return "hello";
});
}
You are doing:
CompletableFuture<String> future = new CompletableFuture<>();
which is documented as:
Creates a new incomplete CompletableFuture.
Essentially, no one completes this CompletableFuture
, so you will always get a timeout, no matter how big it is.
You can also change your code a bit. If you want to run
something, say that explicitly:
private static CompletableFuture<Void> query(Collector collector) {
return CompletableFuture.runAsync(collector::collectStuff);
}
Then please notice that collectStuff
increments a volatile
, but these increments are not atomic.
And you can always use join
instead of get
and not handle checked exceptions (granted there is no join
that takes a timeout).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…