Double-checked locking is the practice of checking a lazy-initialized object's state both before and after a `synchronized` block is entered to determine whether to initialize the object.
In early JVM versions, synchronizing entire methods was not performant, which sometimes caused this practice to be used in its place.
Apart from `float` and `int` types, this practice does not work reliably in a platform-independent manner without additional synchronization of mutable instances.
Using double-checked locking for the lazy initialization of any other type of primitive or mutable object risks a second thread using an uninitialized or partially initialized member while the first thread is still creating it.
The results can be unexpected, potentially even causing the application to crash.
Given significant performance improvements of `synchronized` methods in recent JVM versions, `synchronized` methods are now preferred over the less robust double-checked locking.
I believe that this rule is actually a subset of https://www.securecoding.cert.org/confluence/display/java/TSM03-J.+Do+not+publish+partially+initialized+objects[TSM03-J]. Do we have a rule targeting that? Do we want to implement both?
This rule can be implemented on semantic level, however it will catch only simple cases of this. To do this properly we need to do full escape analysis and implement equivalent of https://www.securecoding.cert.org/confluence/display/java/TSM03-J.+Do+not+publish+partially+initialized+objects[TSM03-J]
=== on 8 Nov 2016, 16:56:41 Ann Campbell wrote:
\[~tibor.blenessy] I considered adding that mapping to this rule, but really see it as tangential to the rule as currently described. Let me know if you disagree.
=== on 8 Nov 2016, 18:41:56 Tibor Blenessy wrote:
Code samples are from book Java Concurrency in Practice and they are available under public domain on this url \http://jcip.net.s3-website-us-east-1.amazonaws.com/listings.html