Is it possible for two ExecutorServices to share a thread pool?

被刻印的时光 ゝ 提交于 2019-12-04 05:50:12
Yuval Adam

To answer your question: no, two ExecutorService objects cannot share a thread pool. However you can share an ExecutorService between your objects, or alternatively create several Executors, as necessary, though this is less recommended.

Best solution: share the Executor between your objects.

Dennis C

Short answer: No.

Longer answer: You will need your own implementation to do that. ExecutorService is an interface and AbstractExecutorService is quite easy to implement. If you want two ExecutorService sharing same ThreadPool (e.g. with different maximum active thread value), you may use proxy pattern to make ThreadPool sharing ExecutorService.

Outlaw Programmer

Can you just pass a reference to the existing ExecutorService to your worker objects?

public class Task implements Runnable {
    private final ExecutorService threadPool;
    private final SubTask[] subtasks;

    public Task(ExecutorService threadPool) {
        this.threadPool = threadPool;
        this.subtasks = createSubtasksIGuess();
    }

    public void run() {
        for(SubTask sub : subtasks)
            threadPool.submit(sub);
    }
}

There are a few good reasons to want to do this, such as separate bounds and metrics per queue. AFAIK, Cassandra 2.1 gained not insignificantly from using an executor service implementation with a shared thread pool; the code is at https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/concurrent/SEPExecutor.java.

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