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;
}
}
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With