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

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -