ExecutorService.submit 的确切行为是什么(就排队请求而言)?

What is the exact behavior of ExecutorService.submit (in terms of queuing requests)?

我想使用一个使用单线程的 ExecutorService。现在我插入请求(通过提交)的速度比该线程可以处理的速度更高。会发生什么?

我特别想知道:

(当然,我可以假设可能会使用一些队列;Oracle 实现只是 "does the right thing";但我实际上想知道是否有一个真正的 "spec" 确定了预期行为)

我认为您是通过 Executors.newSingleThreadExecutor() 获得 ExecutorService

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

所以:

Are there any guarantees on ordering - will tasks be executed in the exact same order?

任务保证按顺序执行。

Is there a (theoretical) limit on which the ExecutorService will start throwing away incoming requests?

在无界队列中运行。 队列的 memory/the 后备存储允许的大小。通常 Integer.MAX_VALUE.

Out of curiosity: what changes when the service is using a pool of threads?

取决于您如何创建 ExecutorService。如果您愿意,您可以使用有界队列创建,或者使用不使用 FIFO 的队列(例如 PriorityBlockingQueue. The documentation for ThreadPoolExecutor 很好地概述了您的不同选项。

如果您使用 Executors.newFixedThreadPool(1);(或 newSingleThreadExecutor())创建了一个固定的线程池 ExecutorService,那么 the Javadoc 会清楚地说明会发生什么。


Are there any guarantees on ordering - will tasks be executed in the exact same order?

固定线程池使用 LinkedBlockingQueue 来保存挂起的任务。这样的队列实现了FIFO策略(先进先出),所以执行的顺序是有保证的。


Is there a (theoretical) limit on which the ExecutorService will start throwing away incoming requests?

引用 Javadoc:

If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

每个传入的请求都将被添加到一个无界队列中,因此没有限制并且不会拒绝任何请求(因此理论上的限制是 Integer.MAX_VALUE)。


Out of curiosity: what changes when the service is using a pool of threads?

如果你的意思是,"what changes if there are more than 1 thread in the fixed thread pool",那就没什么。该队列仍将具有 FIFO 性质,并且对该队列没有限制。否则,这取决于您如何创建线程池。