Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 949
Steve Avatar asked Feb 14 '26 20:02

Steve


1 Answers

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.

like image 84
GhostCat Avatar answered Feb 17 '26 10:02

GhostCat