I try to submit and get 10 Future
s in the same stream. Each one takes 1 second to process and I would like to run them in parallel.
My first try is takes_10_sec()
which runs sequentially and takes 10s.
My second try is takes_1_sec()
which runs in parallel and takes 1s. However it uses an intermediate .collect(Collectors.toList()).stream()
which I don't think is a good way to do it.
Is there another recommended way?
public class FutureStream {
private ExecutorService executor = Executors.newFixedThreadPool(10);;
@Test
public void takes_10_sec() {
IntStream.range(0, 10)
.mapToObj(i -> longTask())
.map(task -> {
try {
return task.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
})
.forEach(System.out::println);
}
@Test
public void takes_1_sec() {
IntStream.range(0, 10)
.mapToObj(i -> longTask())
.collect(Collectors.toList())
.stream()
.map(task -> {
try {
return task.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
})
.forEach(System.out::println);
}
private Future<String> longTask() {
return executor.submit(() -> {
Thread.sleep(1000);
return Thread.currentThread().getName();
});
}
}