简体   繁体   中英

Threadsafe static initialization of ExecutorService

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM