Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect Implementation of Java Future multithreading
    primarykey
    data
    text
    <p>In my servlet I am hitting several URL's to check their status and returning the response to user.</p> <p>Hitting multipe requests takes lot of time: need threads and timouts. But i need my threads to geturn response : using Future for that reason.</p> <p>My code outline: </p> <pre><code>ExecutorService executor = Executors.newFixedThreadPool(10); Future&lt;statusModel&gt; future; for (Map.Entry&lt;String, String&gt; url : urls.entrySet()) { try { future = executor.submit(new CallableRequestStatus(url.getValue())); status = (statusModel) future.get(5, TimeUnit.SECONDS); results.add(status); } catch (InterruptedException | ExecutionException | TimeoutException e) { System.out.println("Error&lt;checkServers&gt;: Timeout OR "+e.getMessage()); } } executor.shutdownNow(); </code></pre> <p>All the results from my callable class is coming in status object which I later add to an arraylist. My problem here is that my approach is blocking me from running all 10 threads at same time. I have to wait 5 secs for getting my status object and then move to next URL.</p> <p>I am thinking my approach is faulty. I tried looking online but I couldnt find any example with custom objects and Arraylist involved.</p> <p>Can anyone help me correct my fault. Thanks in advance</p> <p>Finally Updated my code (thanks to Sotirios Delimanolis and Kevin):</p> <pre><code>ExecutorService executor = Executors.newFixedThreadPool(20); List&lt;Future&lt;statusModel&gt;&gt; futures = new ArrayList&lt;Future&lt;statusModel&gt;&gt;(); for (Map.Entry&lt;String, String&gt; url : urls.entrySet()) { Future&lt;statusModel&gt; future = executor.submit(new CallableRequestStatus(url.getValue())); futures.add(future); } ArrayList&lt;statusModel&gt; results = new ArrayList&lt;statusModel&gt;(); statusModel status; int i=0; for (Map.Entry&lt;String, String&gt; url : urls.entrySet()) { try { status = (statusModel) futures.get(i).get(500, TimeUnit.MILLISECONDS); // do some stuff with status and if(status.getStatusCode()/100 == 2) results.add(status); } catch (InterruptedException | ExecutionException | TimeoutException e) { System.out.println("Error&lt;checkServers&gt;: Timeout OR "+e.getMessage()); } i++; } executor.shutdownNow(); System.out.println("Shutdown: "+executor.isShutdown()); </code></pre> <p>Hope its helpful for someone :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload