Java 8 parallelStream for concurrent Database / REST call
You can do the operation with map
instead of forEach
- that will guarantee thread safety (and is cleaner from a functional programming perspective):
List<String> allResult = partitions.parallelStream()
.map(this::callRestAPI)
.flatMap(List::stream) //flattens the lists
.collect(toList());
And your callRestAPI
method:
private List<String> callRestAPI(List<String> serverList) {
List<String> result = //Do a REST call.
return result;
}
I wouldn't shy away from synchronising access to your ArrayList
. Given that you're accessing a remote service via Rest, I suspect the cost of synchronisation would be negligible. I would measure the effect before you spend time optimising.