rate control in java

▼魔方 西西 提交于 2019-12-05 19:29:25

You can use a ScheduledExecutorService to schedule tasks for a given period of time.

For example, to schedule 100 tasks per second you can say:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(nThreads);
scheduler.scheduleAtFixedRate(mailSender, 0, 10, TimeUnit.MILLISECONDS);

Obviously, you need to track how many tasks have executed and turn off the scheduler after the job is done.

Token bucket algorithm is very easy to implement and use yet very powerful. You can control the throughput at runtime and queue some requests to handle peeks.

Peter Lawrey

The simplest way I can think of is to delay when to send each emails depending on how many are waiting.

final ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(1);
int ratePerSecond = ...

public static void execute(Runnable run) {
   int delay = 1000 * service.getQueue().size() / ratePerSecond;
   service.schedule(run, delay, TimeUnit.MILLISECONDS);
}

This will ensure that the tasks are performed only as close to together as the rate allows.

mR_fr0g

Guava has a RateLimiter class that does exactly that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!