Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy-loaded singleton: Double-checked locking vs Initialization on demand holder idiom

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?

like image 919
Anthony Accioly Avatar asked May 31 '11 14:05

Anthony Accioly


People also ask

What is double-checked locking in Singleton?

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.

What is lazy initialization in Singleton?

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.

Is double-checked locking thread safe?

Double-checked locking is a common pattern for lazy initialization of a field accessed by multiple threads.

How can we create singleton class with double-checked locking?

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.


1 Answers

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.

like image 148
John Vint Avatar answered Sep 29 '22 12:09

John Vint