Search code examples
javaasynchronousnioscheduledexecutorservice

How to get http responses from multiple requests in the order they're recieved


In my application, there are roughly 15 threads that each send an http request to an api endpoint once every 15 seconds; meaning about 1 request a second. These threads should be running indefinitely and only need to be created once. I am unsure how to continuously receive the responses on the main thread so that they can be parsed and dealt with. In trying to research this problem I found several frameworks that look like they could help; ScheduledExecutorService, NIO, Grizzly, AHC. But, I'm paralyzed by the amount of options and am unsure of what to implement.

My main goal is, for each of the 15 requests, to have the request sent off on its own every 15 seconds and receive the response on the main thread as it comes in.


Solution

  • No special frameworks are required for such a simple task. Just create an instance of BlockingQueue (ArrayBlockingQueue looks like the best choice). Each network thread calls queue.put(response) and the main thread makes response=queue.take() in a loop.