I have a method which takes a string as input and returns data from the DB based on the input string. I have an array of strings and I am currently passing each string as input and looping over the entire array
public DataClass getData(String input){
....logic to get the data when string=input from a third party API.
Third party API takes 'input' string and gives out data....
}
public void callerMethod() {
List<String> myStrings = new List<String>();
for(inputStr : myStrings) {
DataClass data = getData(inputStr);
}
}
Above code is the logic I have as of now. I want to change the getData() method calls to concurrent calls instead of looping through the list one after another as this approach is time taking. I am not sure if I can use threads here or if there is any newer approach to achieve this.
ExecutorService.submit()(orinvokeAll()) and fetching the data from the returnedFutures. That's assuming the third-party API can be used in a thread-safe way.Parallel.ForAllthat would take care of that for you, Java 8 provides a similar interface with the new streams API. Unfortunately for you, In Java 7 - you need 2 classes that implement Runnable, one for a worker (consumes from a ConcurrentLinkedQueue) (have like 8 of these or whatever number of cores you have) and one for the DB producer that takes the DB and just produces for it. millimoose's suggestion with Futures is probably a better approach if you want anything more.