I have a requirement to lazy-load resources in a concurrent environment. The code to load the resources should be executed only once.
Both Double-checked locking (using JRE 5+ and the volatile keyword) and Initialization on demand holder idiom seems to fit the job well.
Just by looking at the code, Initialization on demand holder idiom seems cleaner and more efficient (but hey, I'm guessing here). Still, I will have to take care and document the pattern at every one of my Singletons. At least to me, It would be hard to understand why code was written like this on the spot...
My question here is: Which approach s is better? And why? If your answer is none. How would you tackle this requirement in a Java SE environment?
Alternatives
Could I use CDI for this without imposing it's use over my entire project? Any articles out there?
Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle.
Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created.
Double-checked locking is a common pattern for lazy initialization of a field accessed by multiple threads.
As the name suggests, in double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created. By the way, it was broken before Java fixed its memory model issues in JDK 1.5.
As far as readability I would go with the initialization on demand holder. The double checked locking, I feel, is a dated and an ugly implementation.
Technically speaking, by choosing double checked locking you would always incur a volatile read on the field where as you can do normal reads with the initialization on demand holder idiom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With