title: How to prevent client REST API Call block/prioritize certain API calls with Jersey
body: <p>I'm currently making an application that would take information from an api and analyze it and store it in my backend's mongodb. I am using java servlet as the server and jersey as the client calling the api. I ran into a problem where, if someone tells my servlet to tell jersey client to call the api multiple times in rapid succession, the website would simply freeze because it would take ~20 seconds to get everything for only one query. Now that there's spontaneously 5 queries at once, it would take ~100 seconds to finish everything. </p>
  
  <p>Note: I'm not using all of the data I get from the api and giving it to the user immediately. I'm only giving the user data from 1 call, while the other 300 calls are to put all of their data into my database. </p>
  
  <p>tl;dr:
  User click button -> jersey make 400 api calls -> jersey gives data to user from 1 call, then work in back processing the other 399(takes 20 seconds) -> within 20 seconds, someone else clicks button -> he will not get data from that 1 call until the previous person's 399 calls are done.</p>
  
  <p>Can I make it somehow so that the 399 calls are in the background, so that the second user's first api call(where it gives them something to look at) can go ahead and execute before the 399? Will Async work? </p>
  
  <p>Here is my code by the way for the jersey api call:
  Constructor:</p>
  
  <pre><code>public APICaller(){
      client = Client.create();
      sync = RateLimiter.getInstance();
  }
  </code></pre>
  
  <p>Function for calling:</p>
  
  <pre><code>public String call(String url){
      try {
          WebResource webResource = client
             .resource(url);
  
          ClientResponse response = webResource.accept("application/json")
                     .get(ClientResponse.class);
  
          if (response.getStatus() != 200) {
             /*throw new RuntimeException("Failed : HTTP error code : "
              + response.getStatus() + " header : " + response.getHeaders());*/
              System.out.println("Failed : HTTP error code : "
              + response.getStatus() + " header : " + response.getHeaders());
              if(response.getStatus() == 404)
                  return "404";
              if(response.getStatus() == 429)
                  return "429";
              if(response.getStatus() == 503)
                  return "503";
          }
  
          String output = response.getEntity(String.class);
  
          return output;
  
        } catch (Exception e) {
          e.printStackTrace();
        }
      return null;
  }
  </code></pre>
  
  <p>PS: I'm sorry if my code looks horrendous, but I'm still learning how to use Jersey. Please let me know if the code should be improved in any way. Thanks.</p>