I’m looking for a way to limit access to a method in java to no more than once every X seconds. Here’s my situation :
I want to run this code in parallel with multiple threads :
private MyService service;
public void run() {
// Send request to remote service
InputStream response = service.executeRequest();
// Process response
... some more code
}
The executeRequest() method sends an http request to a remote server (which isn’t mine, I have no access to its implementation) and waits for the response from the server. It then does some processing of the data.
I would like to have many threads run this in parallel. My problem is that the remote server will crash if too many requests are sent simultaneously. So I want some way of making sure that the executeRequest() method will never be called more than once every second.
Do you know how I could do that in java ? Thanks
You could use a Semaphore to throttle the number of threads able to call executeRequest():
http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/Semaphore.html
The executing thread could increment the semaphore prior to entering the execute and other threads could wait for it to fall to either 0 or a number which reflects how many are allowed to run in parallel.
A Timertask:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html
Could be used to decrement the semaphore after 3 seconds… Throttling the entry to no more than 1 new entrant every 3 seconds: