我想使用一个使用单线程的ExecutorService
。现在我插入请求(通过提交)的速度比该线程可以处理的速度更高。会发生什么?
我特别想知道:
- 是否有任何顺序保证 - 任务会以完全相同的顺序执行吗?
- ExecutorService 开始丢弃传入请求是否存在(理论上的)限制?
- 出于好奇:当服务使用线程池时会发生什么变化?
(当然,我可以假设可能会使用一些队列;并且 Oracle 实现只是“做正确的事”;但我实际上想知道是否有一个真正的“规范”确定了预期的行为)
最佳答案
如果您使用 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?
如果你的意思是,“如果固定线程池中有超过 1 个线程,会有什么变化”,那么什么也没有。该队列仍将具有 FIFO 性质,并且对该队列没有限制。否则,这取决于您如何创建线程池。
关于java - ExecutorService.submit 的确切行为是什么(在排队请求方面)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690476/