Correct Implementation of Java Future multithreading

后端 未结 1 1457
执笔经年
执笔经年 2020-12-21 08:53

In my servlet I am hitting several URL\'s to check their status and returning the response to user.

Hitting multipe requests takes lot of time: need threads and timo

相关标签:
1条回答
  • 2020-12-21 09:42

    You need to submit everything upfront, then wait separately. As below, exception handling removed for clarity:

    ExecutorService executor = Executors.newFixedThreadPool(10);
    List<Future<statusModel>> futures = new ArrayList<>();
    
    for (Map.Entry<String, String> url : urls.entrySet())
    {
        futures.add(executor.submit(new CallableRequestStatus(url.getValue())));
    }
    for (Future<statusModel> f : futures) {
        results.add((statusModel) f.get(5, TimeUnit.SECONDS));
    }
    
    0 讨论(0)
提交回复
热议问题