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?
Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:
Draconian synchronization:
This solution requires that every thread be synchronized when in reality only the first few need to be.
Double check synchronization:
This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.
Initialization on Demand:
This solution takes advantage of the Java memory model’s guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time
getInstanceis called,InstanceHolderwill be loaded andinstancewill be created, and since this is controlled byClassLoaders, no additional synchronization is necessary.