Theory:
Token Bucket Algorithm is a way to limit a download's bandwidth. You should read this article : it explains the use of this algorithm.
Implementations:
RateLimiter from Google Guava
Google Guava 22.0 include a RateLimiter class but it is still in beta.
From api documentation:
As an example, imagine that we have a list of tasks to execute, but we don't want to submit more than 2 per second:
final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second" void submitTasks(List<Runnable> tasks, Executor executor) { for (Runnable task : tasks) { rateLimiter.acquire(); // may wait executor.execute(task); } }
As another example, imagine that we produce a stream of data, and we want to cap it at 5kb per second. This could be accomplished by requiring a permit per byte, and specifying a rate of 5000 permits per second:
final RateLimiter rateLimiter = RateLimiter.create(5000.0); // rate = 5000 permits per second void submitPacket(byte[] packet) { rateLimiter.acquire(packet.length); networkService.send(packet); }
TimedSemaphore from Apache Commons Lang v3
Apache Commons Lang v3 include a TimedSemaphore class that can be used to implement a rate limit.