英文:
Eager initializations of Java libs
问题
我正在使用Java并发库中的ExecutorService,但我不确定是否应该如下主动初始化ExecutorService。
public class Opts extends Runnable {
//...
private ExecutorService executor = Executors.newFixedThreadPool(10);
//...
}
通常情况下,我不会主动初始化第三方依赖项或我的自定义类,但在这种情况下,它来自于Java,并且我猜测它的依赖性很小。我应该选择什么?
用例:Opts类也是一个Runnable,它监听事件。当事件发生时,它使用ExecutorService来执行它。
英文:
I am using ExecutorService from Java concurrent libs, but I am not sure if I should initialize ExecutorService eagerly as follows.
public class Opts extends Runnable {
//...
private ExecutorService executor = Executors.newFixedThreadPool(10);
//...
}
Normally I would not initialize 3rd party dependencies or my own class but in this case, it is from Java and guessing it's dependency is minimal. What should I prefer?
Usecase: Opts class is also Runnable and listens events. When an event comes, it executes it using ExecutorService.
答案1
得分: 3
你可以选择你喜欢的方式。由你自己来决定。
但我建议你保持简单。除非有充分的理由使用延迟初始化,否则使用急切初始化。
(在这种情况下,一个充分的理由可能是线程池不太可能被使用,或者你的应用程序需要快速启动是一个至关重要的要求。)
> 通常情况下,我不会初始化第三方依赖项或我的自定义类,但在这种情况下...
你可能需要重新考虑这一点。我不确定是否有理由一概而论。特别是这可能会使事情变得比必要的复杂。
英文:
You can prefer what you like. It is up to you to make up your own mind.
But I would recommend that you keep it simple. Use eager initialization unless there is a good reason to use lazy initialization.
(A good reason in this case might be that the thread pool is unlikely to needed, or that fast startup for your application is a critical requirement.)
> Normally I would not initialize 3rd party dependencies or my own class but in this case ...
You might want to review that. I am not sure that a blanket preference is justified. Especially one that may make things more complicated than they need to be.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论