Eager initializations of Java libs Java库的急切初始化

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月6日 15:14:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63278583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定