多个 newSingleThreadExecutor 与 ExecutorService 的 newFixedThreadPool
Multiple newSingleThreadExecutor vs. newFixedThreadPool of ExecutorService
在我的应用程序中,我有 4 个不同的进程,这些进程 运行 永久地带有一些小的停顿。
当前版本的代码在单独的老式线程中执行每个进程:
Thread nlpAnalyzer = new Thread(() -> {
// infine lop for auto restore in case of crash
//noinspection InfiniteLoopStatement
while (true) {
try {
// this method should run permanently, pauses implemented internally
NLPAnalyzer.analyzeNLP(dbCollection);
} catch (Exception e) {
e.printStackTrace();
}
}
});
nlpAnalyzer.setName("im_nlpAnalyzer");
nlpAnalyzer.start();
现在我想使用 ExecutorService
重构这段代码。为此,我至少可以使用两种方法:
newFixedThreadPool(numOfProc)
;
numOfProc * newSingleThreadExecutor()
.
我的问题:
- 为什么我应该更喜欢一个选项而不是另一个选项?
- 生成X个线程的线程池和生成X个
newSingleThreadExecutor
s哪个更容易接受?
- 每种方法的优缺点?
鉴于每个任务都是一个无限循环,我会使用
newCachedThreadPool();
这将为每个需要它的任务创建一个线程(不再需要)
使用单个线程池的好处是你可以单独关闭池,或者给每个线程一个名字,但如果你不需要这个,它只是开销。
注意:您可以使用 setName("My task") 更改线程的名称,这可能对 debugging/profiling 有用。
使用 ExecutorService 的技巧之一是它捕获任何未捕获的 exception/errors 并将其放入返回的 Future
对象中。这个 Future
通常会被丢弃,这意味着如果您的任务意外终止,它也可能会静默执行。
我建议您在循环外执行 try/catch(Throwable) 并记录它,以便您可以查看线程是否意外终止。例如 OutOfMemoryError
除了关闭单个执行程序外,我看不到以下选项有任何好处。
numOfProc * newSingleThreadExecutor()
但你有更多的选择。我更喜欢 Executors
中的以下三个选项之一。
newFixedThreadPool
newCachedThreadPool
newWorkStealingPool
相关查询请参考以下SE问题:
Java's Fork/Join vs ExecutorService - when to use which?
Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()
在我的应用程序中,我有 4 个不同的进程,这些进程 运行 永久地带有一些小的停顿。
当前版本的代码在单独的老式线程中执行每个进程:
Thread nlpAnalyzer = new Thread(() -> {
// infine lop for auto restore in case of crash
//noinspection InfiniteLoopStatement
while (true) {
try {
// this method should run permanently, pauses implemented internally
NLPAnalyzer.analyzeNLP(dbCollection);
} catch (Exception e) {
e.printStackTrace();
}
}
});
nlpAnalyzer.setName("im_nlpAnalyzer");
nlpAnalyzer.start();
现在我想使用 ExecutorService
重构这段代码。为此,我至少可以使用两种方法:
newFixedThreadPool(numOfProc)
;numOfProc * newSingleThreadExecutor()
.
我的问题:
- 为什么我应该更喜欢一个选项而不是另一个选项?
- 生成X个线程的线程池和生成X个
newSingleThreadExecutor
s哪个更容易接受? - 每种方法的优缺点?
鉴于每个任务都是一个无限循环,我会使用
newCachedThreadPool();
这将为每个需要它的任务创建一个线程(不再需要)
使用单个线程池的好处是你可以单独关闭池,或者给每个线程一个名字,但如果你不需要这个,它只是开销。
注意:您可以使用 setName("My task") 更改线程的名称,这可能对 debugging/profiling 有用。
使用 ExecutorService 的技巧之一是它捕获任何未捕获的 exception/errors 并将其放入返回的 Future
对象中。这个 Future
通常会被丢弃,这意味着如果您的任务意外终止,它也可能会静默执行。
我建议您在循环外执行 try/catch(Throwable) 并记录它,以便您可以查看线程是否意外终止。例如 OutOfMemoryError
除了关闭单个执行程序外,我看不到以下选项有任何好处。
numOfProc * newSingleThreadExecutor()
但你有更多的选择。我更喜欢 Executors
中的以下三个选项之一。
newFixedThreadPool
newCachedThreadPool
newWorkStealingPool
相关查询请参考以下SE问题:
Java's Fork/Join vs ExecutorService - when to use which?
Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()