I have this piece of code that I have two questions.
- I'm not sure why I see TimeoutException as there's no blocking anywhere.
- What I'm trying to achieve with the
Collector
is I have a class that will go in to collect a bunch of metrics and after theCompletableFuture
is completely done then I would executeCollector
to release metrics. Isfinally
guaranteed that it will be executed last as I think.get()
is supposed to be blocked until it's finished?
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Supplier;
public class FutureWithCollector
{
public static void main(String[] args) throws ExecutionException, InterruptedException
{
Collector collector = new Collector();
finalize(() -> query(collector), collector);
}
private static void finalize(Supplier<CompletableFuture<String>> submission, Collector collector) throws ExecutionException, InterruptedException
{
ExecutorService executorService = Executors.newFixedThreadPool(1);
CompletableFuture<String> s = CompletableFuture.supplyAsync(submission, executorService).thenCompose(Function.identity());
try {
String result = s.get(1000, TimeUnit.MILLISECONDS);
System.out.println(result);
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
System.out.println(collector.getI());
}
}
private static CompletableFuture<String> query(Collector collector)
{
CompletableFuture<String> future = new CompletableFuture<>();
return future.thenApply(r -> {
collector.collectStuff();
return "Hello";
});
}
}
class Collector
{
private volatile int i;
public void collectStuff()
{
i++;
}
public int getI()
{
return i;
}
}
Output
java.util.concurrent.TimeoutException
at java.util.concurrent.CompletableFuture.timedGet(CompletableFuture.java:1771)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1915)
at FutureWithCollector.finalize(FutureWithCollector.java:23)
at FutureWithCollector.main(FutureWithCollector.java:15)
0