user8193619
user8193619

Reputation:

How to improve performance of multi threading

I have googled and found the best way to use multithreading but its failing for a 100 records it giving 504 status code. Is there any scope to improve the below code?

@Scheduled(fixedRate = 5000)
public ResponseEntity<Object> getData(List<JSONObject> getQuoteJson, String username,
                                      String authorization) throws ParseException, IOException, Exception {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("Access-Control-Allow-Origin", "*");
    CompletableFuture<JSONArray> future = null;
    JSONArray responseArray = new JSONArray();
    try {
        executor = Executors.newFixedThreadPool(getQuoteJson.size());
        for (int i = 0; i < getQuoteJson.size(); i++) {
            JSONObject jsonObject = (JSONObject) getQuoteJson.get(i);
            future = CompletableFuture.supplyAsync(() -> {
                JSONObject response = asynCallService.getDataAsyncService(jsonObject, productCode, authorization);
                responseArray.add(response);
                return responseArray;
            }, executor);
        }
        return new ResponseEntity<Object>(future.get(), responseHeaders, HttpStatus.OK);
    } catch (Exception e) {
        throw e;
    } finally {
        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (Exception e) {
        }
    }

}

Upvotes: 1

Views: 213

Answers (2)

Wow all of this to iterate asynchronly on a list ?

this is i think more likely to be what you searched :

HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
final JSONArray responseArray = new JSONArray();
getQuoteJson.parallelStream().map(e->asynCallService.getDataAsyncService(e, productCode, authorization)).forEach(responseArray::add);
return new ResponseEntity<Object>(responseArray, responseHeaders, HttpStatus.OK);

Upvotes: 1

xingbin
xingbin

Reputation: 28289

Do not create and shutdown executor every time, use a singleton cached thread pool. Since creating threads repeatly is unecessary and expensive, and the benefit of thread pool is keeping threads existing.

Upvotes: 3

Related Questions