I am having the following method:
public String getResult() {
List<String> serversList = getServerListFromDB();
List<String> appList = getAppListFromDB();
List<String> userList = getUserFromDB();
return getResult(serversList, appList, userList);
}
Here I am calling three method sequentially which in turns hits the DB and fetch me results, then I do post processing on the results I got from the DB hits. I know how to call these three methods concurrently via use of Threads
. But I would like to use Java 8 Parallel Stream
to achieve this. Can someone please guide me how to achieve the same via Parallel Streams?
EDIT I just want to call the methods in parallel via Stream.
private void getInformation() {
method1();
method2();
method3();
method4();
method5();
}
Not quite clear what do you mean, but if you just want to run some process on these lists on parallel you can do something like this:
(it will print most lengthy elements from each list).
foreach
is what used forside-effects
, you can callforeach
on aparallel stream
. ex:However,
parallelStream
uses the commonForkJoinPool
which is arguably not good forIO-bound
tasks.Consider using a
CompletableFuture
and supply an appropriateExecutorService
. It gives more flexibility (continuation
,configuration). For ex:You may utilize
CompletableFuture
this way:As already mentioned, a standard parallel stream is probably not the best fit for your use case. I would complete each task asynchronously using an ExecutorService and "join" them when calling the getResult method: