title: Waiting at most X seconds for Async EJBs
body: <p>I have a "client" <code>EJB</code> that invokes 4 <code>Asynchronous</code> <code>EJB</code>s and should give them all 5 seconds to run. After 5 seconds the "client" EJB collects the ready results from <code>Future</code> object that finished running, and returns output.</p>
  
  <p>I have a problem with the "waiting" in client part. I tried to invoke <code>future.get(5, TimeUnit.MILLISECONDS)</code>
  It seems like sometimes async <code>EJB</code>s <strong>start to run after</strong> the timeout. 
  Is there a correct way to do it?</p>
  
  <p>1) Collect <code>Future</code> objects in <code>Map</code>:</p>
  
  <pre><code>    Map&lt;String, Future&gt; futureMap = new HashMap&lt;String, Future&gt;();
      for (String userID: users) {
              Future&lt;Set&lt;FrontPageData&gt;&gt; test = util.asyncGetData(userID);
              futureMap.put(serviceID, test);
  
      }
      return futureMap;
  </code></pre>
  
  <p>2) Then I get output with timeout from <code>Future</code> objects </p>
  
  <pre><code>    final long now = Calendar.getInstance().getTimeInMillis();
      final long end = now + TimeUnit.SECONDS.toMillis(5)
      Map&lt;String, Object&gt; output = new HashMap&lt;String, Object&gt;();
      Object data;
      for (String userID: futureMap.keySet()) {
          Future future= futureMap.get(userID);
          try {
              //check how much time left till the end
              long timeout = end - Calendar.getInstance().getTimeInMillis();
              data = future.get(timeout, TimeUnit.MILLISECONDS);
              output.put(userID, data);
          } catch (Exception e) {//write to logs
          } 
      }
      return output;
  }
  </code></pre>
  
  <p>thank you</p>