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-
private static volatile ExecutorService executor;
is it required to make our ExecutorService
as Volatile
to achieve above behavior.
Below is the factory class
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;
}
}