1

Question about ScheduledExecutorService.shceduleAtFixedRate - I schedule taskA to run every 500 millis, which blocks for 1000 millis. Now subsequent executions aren't gonna wait the extra 500 millis, but rather commence immediately after the previous one.

taskA acquires an intrinsic lock, which is also (attempted) acquired by a different thread. Since intrinsic locks have no fairness guarantees this thread is running a risk of starvation, so here's my question: Is there a good/clean way to avoid this risk? E.g. schedule the task to run every 1500 millis (doesn't sound very waterproof)? Or do we expect the lock acquisition to exhibit a kind of "amortized fairness"?

4

1 回答 1

2

是的,您可以使用scheduleWithFixedDelay

创建并执行一个周期性操作,该操作首先在给定的初始延迟之后启用,随后在一个执行终止和下一个执行开始之间具有给定的延迟。如果任务的任何执行遇到异常,则后续执行将被抑制。否则,任务只会通过取消或终止执行者来终止。

因此,您给出的延迟是最后一个结束与下一个开始之间的时间 - 即运行之间没有重叠。

于 2019-02-12T15:56:33.680 回答