The double checked locking idiom is sometimes used to provide lazy initialization in multithreaded code. The code shown below ensures that only one instance of the Helper
object can exist at a particular time in a multithreaded context.
Code Block |
---|
// Correct multithreaded version class Foo { private Helper helper = null; public synchronized Helper getHelper() { if (helper == null) { helper = new Helper(); } return helper; } // otherOther functions and members... } |
The double checked locking idiom eliminates the synchronization to achieve performance gains. If implemented incorrectly, it may offer no such benefits and lead to erroneous or no ineffective synchronization.
Wiki Markup |
---|
According to the Java Memory Model (discussion reference) \[[Pugh 04|AA. Java References#Pugh 04]\]: |
...