title: Making volatile Executor class in multi-threaded environment
body: <p>In my spring based application we are initializing threadPool using ExecutorService for concurrent task execution.We don't want the threadPool to be initialised multiple times in case of multithreaded environment, for which we are making our factory class as Singleton.
  below is the factory implementation which we are using for threadPool initialization. Sonar analysis is giving a Bug warning as "Remove the "volatile" keyword from this field" for below line-
  <code>private static volatile ExecutorService executor;</code>
  is it required to make our <code>ExecutorService</code> as <code>Volatile</code> to achieve above behavior.
  Below is the factory class</p>
  
  <pre><code>public class ThreadPoolExecutorFactory {
  
      /** The executor. */
      private static volatile ExecutorService executor;
  
      /**
       * Instantiates a new thread pool executor factory.
       */
      private ThreadPoolExecutorFactory() {
          // preventing Singleton object instantiation from outside
      }
  
      /**
       * Gets the executor.
       *
       * @return the executor
       */
      public static ExecutorService getExecutor( ) {
          if(executor == null) {
              synchronized (ThreadPoolExecutorFactory.class) {
                  if(executor == null) {
                      executor = Executors.newCachedThreadPool();
                      Runtime.getRuntime().addShutdownHook(new Thread() {
                          @Override
                          public void run() {
                              executor.shutdown();
                          }
                      });
                  }
              }
          }
          return executor;
      }
  }
  </code></pre>