multithreading - Java 8 parallelStream for concurrent Database / REST call -
here using javaparallel stream iterate through list , calling rest call each list element input. need add results of rest call collection using arraylist
. code given below working fine except non-thread-safety of arraylist cause incorrect results, , adding needed synchronization cause contention, undermining benefit of parallelism.
can please suggest me proper way of using parallel stream case.
public void mymethod() { list<list<string>> partitions = getinputdata(); final list<string> allresult = new arraylist<string>(); partitions.parallelstream().foreach(serverlist -> callrestapi(serverlist, allresult); } private void callrestapi(list<string> serverlist, list<string> allresult) { list<string> result = //do rest call. allresult.addall(result); }
you can operation map
instead of foreach
- guarantee thread safety (and cleaner functional programming perspective):
list<string> allresult = partitions.parallelstream() .map(this::callrestapi) .flatmap(list::stream) //flattens lists .collect(tolist());
and callrestapi method
:
private void callrestapi(list<string> serverlist) { list<string> result = //do rest call. return result; }
Comments
Post a Comment