Threadsafe static initialization of ExecutorService

主宰稳场 提交于 2019-12-11 01:18:28

问题


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?


回答1:


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.




回答2:


The most simplest thread-safe initialization is to use a static final class variable like this:

public class Check {
  public static final Executor EXECUTOR = new ThreadPoolExecutor(5, "read this val from file", 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
  // ...
}

Add a Getter if you prefer that style.

What you are trying is a lazy initialization, which is best done with enums (as by GhostCat's answer). But for your use-case lazy initialization is not necessary, as the executor initializes fast and with low footprint.



来源:https://stackoverflow.com/questions/45009918/threadsafe-static-initialization-of-executorservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!