ExecutorService:如果我向 Executor 提交()太多任务会发生什么?

问题描述 投票:0回答:1

看起来 ExecutorService 内部使用了阻塞队列。

我只向 ExecutorService 分配 2 个线程,如下所示:

ExecutorService executor = Executors.newFixedThreadPool(2);

如果我不断地提交任务会发生什么?如果阻塞队列已满,是否会阻止更多任务添加?提交这么多任务会不会影响记忆力?有什么影响?询问是因为我在我的代码中看到这种情况发生,所以想知道有什么副作用。

Future<> future = executorService.submit(callableTask);
java multithreading concurrency executorservice
1个回答
0
投票

您可以在静态方法中看到

ExecutorSevice
的实现,例如
Executors.newFixedThreadPool()

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                              0L, TimeUnit.MILLISECONDS,
                              new LinkedBlockingQueue<Runnable>());
}

以及

ThreadPoolExecutor
LinkedBlockingQueue
相应的构造函数如下。

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
   this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}
public LinkedBlockingQueue() {
   this(Integer.MAX_VALUE);
}

因此,如果您继续向线程池提交任务(假设您提交的任务需要花费大量时间),最终可能会导致 OutOfMemoryError (OOM)。

但是,在不知道您面临的具体情况的情况下,我不建议将其替换为

Executors.newCachedThreadPool()
,因为它会不断创建新线程。

相反,我建议您根据您的需求创建自己的

ThreadPoolExecutor

© www.soinside.com 2019 - 2024. All rights reserved.