Class which is implemented with Singleton Pattern
is as follows, when multiple threads access this method only one thread has to create the instance so all I am doing is synchronising the method
private static synchronized FactoryAPI getIOInstance(){
if(factoryAPI == null){
FileUtils.initWrapperProp();
factoryAPI = new FactoryAPIImpl();
}
return factoryAPI;
}
which I feel is unnecessary because only for the first time the instance would be created and for the rest of the time the instance created already would be returned. When adding synchronised
to block allows only one thread to access the method at a time.
The getIOInstance
does two jobs
i) Initialising properties and
ii) Creating a new instance for the first time
So, I'm trying to do block level synchronisation
here like the following
private static FactoryAPI getIOInstance(){
if(factoryAPI == null){
synchronised {
if(factoryAPI == null){
FileUtils.initWrapperProp();
factoryAPI = new FactoryAPIImpl();
}
}
}
return factoryAPI;
}
I prefer the second one to be the right one. Am I using it in a right way? Any suggestions are welcome.