【发布时间】:2017-10-06 03:08:42
【问题描述】:
我应该在每个方法调用中创建新的 ExecutorService 还是每个类都使用一个?就性能而言,哪个是首选?
public class NotificationService {
public void sendNotification(User recipient) {
ExecutorService notificationsPool = Executors.newFixedThreadPool(10);
// code
notificationsPool.shutdown();
}
}
或者
public class NotificationService {
ExecutorService notificationsPool = Executors.newFixedThreadPool(10);
public void sendNotification(User recipient) {
// code
}
}
【问题讨论】:
-
你不会根据性能选择这个。您根据需要选择此选项。您是否需要 10 个新线程才能向用户发送通知?如果你只使用其中一个,只使用一次(假设这是向用户发送通知会做的事情),那么拥有 10 个可重用线程池有什么意义?
-
用户可能与超过 1 个键相关。但是,在发布之前修改的代码示例不是很好。
标签: java multithreading concurrency threadpool executorservice