ScheduledThreadPoolExecutor
扩展了 ThreadPoolExecutor
,但是 ScheduledThreadPoolExecutor
的构造函数较少,提供了无限的延迟队列,这样如果我提交太多任务,可能会导致 jvm OOM,为什么它不提供有限队列和拒绝策略(无法提交新任务时拒绝)?
最佳答案
Why does not it provide a finite queue and reject policy(reject when can't submit new task)?
您需要询问设计师,但他们决定不支持这一事实表明他们认为这没有用。 (或者至少,没有有用足以证明额外的复杂性是合理的。)
还有一个原因。 ScheduledThreadPoolExecutor
的实现取决于队列以正确的顺序返回元素。如果您查看源代码,您会发现它为此使用了自定义队列类。有一条评论是这么说的:
Using a custom queue (
DelayedWorkQueue
), a variant of unboundedDelayQueue
. The lack of capacity constraint and the fact thatcorePoolSize
andmaximumPoolSize
are effectively identical simplifies some execution mechanics (seedelayedExecute
) compared toThreadPoolExecutor
.
此外,很明显,延迟队列实现必须具有特定的操作属性,以便执行器正常有效地工作。这可能就是为什么他们不允许您提供自己的队列实现。
最后,如果您希望应用程序对延迟队列大小施加限制,则可以在安排新任务之前使用 yourPool.getQueue().length()
检查队列长度。
关于java - 为什么ScheduledThreadPoolExecutor不提供有限队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429073/