Guys,
What about this?
Why is this still broken?
There is an excellent article on that double checked locking issue:
http://www-106.ibm.com/developerworks/java/library/j-dcl.html?loc=j and the classic one:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html The trouble with the out of order writes (allocating the memory and then executing the constructor) is that the normal double checked locking checks the object against null if (instance == null). That might cause timing issues and returning an object that has not been correctly initialized.
but here we check a Boolean (boolean assignments are atomic).
In this scenario the Boolean created is set to true INSIDE of the sync block.
The first thread exiting the sync block will flush properly the created (setting it to true). So if the second thread passed the first check and got blocked because the first one is in the sync block, it will not pass the second check though.
I don�t see how a compiler could optimize the code above?
In the listing 7 of the first link I mentioned above there is a broken �fix� for the double checked idiom because of the JIT compiler optimization. But the solutions are different. Compare:
It seems obvious that the compiler would optimize it (move the line 5 inside of the sync block).
Where is the trouble in my snippet?
Any suggestions?
Thanks folks,
Joe
[ May 13, 2005: Message edited by: Joe Boxer ]
[ May 13, 2005: Message edited by: Joe Boxer ]
[ May 13, 2005: Message edited by: Joe Boxer ]