我應該在每個方法調用中創建新的ExecutorService還是每個類使用一個?在性能方面哪個是首選?ExecutorService - 在方法中創建新實例vs每個類創建一個實例
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個以上的密鑰相關。但是,這不是在發佈之前修改的好代碼示例。 – Justas