Skip to main content
improved formatting
Source Link
Hosam Aly
  • 42.6k
  • 38
  • 148
  • 183

I want to implement lazy initialization for multithreading in Java.
I have some code of the sort:

class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { Helper h; synchronized(this) { h = helper; if (h == null) synchronized (this) { h = new Helper(); } // release inner synchronization lock helper = h; } } return helper; } // other functions and members... } 

class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { Helper h; synchronized(this) { h = helper; if (h == null) synchronized (this) { h = new Helper(); } // release inner synchronization lock helper = h; } } return helper; } // other functions and members... } 

And I'm getting the the "Double-Checked Locking is Broken" declaration.
How can I solve this?

I want to implement lazy initialization for multithreading in Java.
I have some code of the sort:

class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { Helper h; synchronized(this) { h = helper; if (h == null) synchronized (this) { h = new Helper(); } // release inner synchronization lock helper = h; } } return helper; } // other functions and members... } 

And I'm getting the the "Double-Checked Locking is Broken" declaration.
How can I solve this?

I want to implement lazy initialization for multithreading in Java.
I have some code of the sort:

class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { Helper h; synchronized(this) { h = helper; if (h == null) synchronized (this) { h = new Helper(); } // release inner synchronization lock helper = h; } } return helper; } // other functions and members... } 

And I'm getting the the "Double-Checked Locking is Broken" declaration.
How can I solve this?

Source Link
monsieurBelbo
  • 737
  • 1
  • 8
  • 16

How to solve the "Double-Checked Locking is Broken" Declaration in Java?

I want to implement lazy initialization for multithreading in Java.
I have some code of the sort:

class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { Helper h; synchronized(this) { h = helper; if (h == null) synchronized (this) { h = new Helper(); } // release inner synchronization lock helper = h; } } return helper; } // other functions and members... } 

And I'm getting the the "Double-Checked Locking is Broken" declaration.
How can I solve this?