Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out-of-order writes for Double-checked locking

In the examples mentioned for Out-of-order writes for double-checked locking scenarios (ref: IBM article & Wikipedia Article)

I could not understand the simple reason of why Thread1 would come of out synchronized block before the constructor is fully initialized. As per my understanding, creating "new" and the calling constructor should execute in-sequence and the synchronized lock should not be release till all the work in not completed.

Please let me know what I am missing here.

like image 230
Sandeep Jindal Avatar asked Dec 08 '22 23:12

Sandeep Jindal


1 Answers

The constructor can have completed - but that doesn't mean that all the writes involved within that constructor have been made visible to other threads. The nasty situation is when the reference becomes visible to other threads (so they start using it) before the contents of the object become visible.

You might find Bill Pugh's article on it helps shed a little light, too.

Personally I just avoid double-checked locking like the plague, rather than trying to make it all work.

like image 87
Jon Skeet Avatar answered Jan 02 '23 10:01

Jon Skeet