Please clarify my queries regarding Singleton and Multithreading:
- What is the best way to implement Singleton in Java, in a multithreaded environment?
- What happens when multiple threads try to access
getInstance()
method at the same time? - Can we make singleton's
getInstance()
synchronized
? - Is synchronization really needed, when using Singleton classes?
You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.
Source : Effective Java -> Item 2
It suggests to use it, if you are sure that class will always remain singleton.