i'm trying to process some amount of data concurrently using CompletableFuture
and Stream
So far i have:
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("start");
List<String> collect = Stream.of("1", "2", "3", "4", "5",
"6", "7")
.map(x -> CompletableFuture.supplyAsync(getStringSupplier(x)))
.collect(Collectors.toList())
.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
System.out.println("stop out!");
}
public static Supplier<String> getStringSupplier(String text) {
return () -> {
System.out.println("start " + text);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("stop " + text);
return "asd" + text;
};
}
And output is fine :
start
start 1
start 4
start 3
start 2
start 5
start 6
start 7
stop 4
stop 1
stop 5
stop 2
stop 6
stop 3
stop 7
stop out!
However right now i want to add timeout to that job. Lets say it should be canceled after 1 SECOND. And return null or some other value to collect
list. (I would prefer some value indicating cause).
How can i achieve that ?
Thanks for help in advance.
I have found the way of doing that:
It returns :
What do you think about that, can you spot any flaws of that solution ?