2

I need to limit the number of HTTP calls per second to max 10. This is as per the allowed quota.

Does HttpClient has some feature for this? Or any custom implementation would also do.

Vipul
  • 816
  • 9
  • 11

1 Answers1

3

You might try the ScheduledThreadPoolExecutor.

From the javadoc:

A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically

You would simply use the schedule method and pass it a Runnable, where the Runnable makes your call via the HttpClient. You could schedule your Runnable to run 10 times per second, or as needed. The Executor will queue up your calls over the HttpClient, and only run a max of 10 per second.

StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
  • HTTP calls in my scenario can't be concurrent. They all need to be in series one after the another. Using ScheduledThreadPoolExecutor will run different threads parallelly. – Vipul Jan 06 '17 at 23:53
  • set the [constructor](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#ThreadPoolExecutor(int,%20int,%20long,%20java.util.concurrent.TimeUnit,%20java.util.concurrent.BlockingQueue)) argument `maxPoolSize` to one. There will be no concurrent threads. Alternately call [setMaxPoolSize()](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#setMaximumPoolSize(int)). – StvnBrkdll Jan 07 '17 at 01:27