In Java, if there are several operations that the running sequence does not matter, we could create a thread for each operation to run them in parallel to improve performance
However, to create and use threads directly there are a lot of boilerplate code. Using parallel stream will achieve the goal of running code in parallel in a relatively simply way
First let's look into how long would it take to call 3 web urls sequentially:
public static void main(String[] args) { Date startTime = new Date(); HttpClient httpClient = HttpClient.newBuilder().build(); HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create("http://www.nfl.com")).build(); String response = ""; try { HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); response = httpResponse.body(); } catch (Exception e) { e.printStackTrace(); } httpRequest = HttpRequest.newBuilder().uri(URI.create("http://www.nba.com")).build(); try { HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); response = httpResponse.body(); } catch (Exception e) { e.printStackTrace(); } httpRequest = HttpRequest.newBuilder().uri(URI.create("http://www.mlb.com")).build(); try { HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); response = httpResponse.body(); } catch (Exception e) { e.printStackTrace(); } Date endTime = new Date(); System.out.println("Time taken: " + (endTime.getTime() - startTime.getTime())); }
It will take:
Time taken: 904
We can make use of parallel stream to speed up the process
First create an ArrayList and add each operation arguments. Next call the parallelStream method to create a parallel Stream. Then define the same calling logic inside the map method. Finally call the collect method to get the responses as a list:
public static void main(String[] args) { Date startTime = new Date(); List<String> list = new ArrayList<>(); list.add("http://www.nfl.com"); list.add("http://www.nba.com"); list.add("http://www.mlb.com"); List<String> listResponse = new ArrayList<>(); listResponse = list.parallelStream().map(strURL -> { HttpClient httpClient = HttpClient.newBuilder().build(); HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create(strURL)).build(); String response = ""; try { HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); response = httpResponse.body(); } catch (Exception e) { e.printStackTrace(); } return response; }).collect(Collectors.toList()); Date endTime = new Date(); System.out.println("Time taken: " + (endTime.getTime() - startTime.getTime())); }
This time it takes much less time:
Time taken: 431