问题描述
我试图基于按需初始化"持有人惯用语创建一个线程安全的单例类.这是我的代码
I am trying to create a threadsafe singleton class based on Initialization-on-demand holder idiom . Here is my code
public class Check{
private Check(){ }
private static class Provider {
static final ExecutorService INSTANCE = new ThreadPoolExecutor(5, "read this val from file", 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
}
public static ExecutorService getInstance() {
return Provider.INSTANCE;
}
}
我的期望是以线程安全的方式初始化ExecutorService,并且那里只有一个实例(静态).
My expectation is to initialize ExecutorService in a threadsafe manner and only one instance should be there (static).
此代码是否达到了目标-还是需要任何更改?
Is this code achieving that - or are any changes required?
推荐答案
根据SEI 指南您的方法很好.
According to the SEI guidelines your approach is fine.
但是由于我们有枚举,因此可以使用枚举的简单方法:
But since we have enums, the easy way to get that to use enums:
public enum Service {
INSTANCE;
private final ExecutorService service = ...
public getService() { return service ; }
如果您想变得真正聪明,还可以定义一个枚举实现的接口;因为这样您以后可以模拟使用该单例.这对于使用相同线程执行服务替换编写单元测试非常有帮助.
And if you want to be really smart, you also define an interface which that enum implements; because that allows you to later mock usages of that singleton. Which becomes extremely helpful for writing unit tests using a same-thread-exectution-service replacement.
这篇关于ExecutorService的线程安全静态初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!