5

Reference article on JMM

It is worth noting that broken techniques like double-checked locking are still broken under the new memory model, and that "fixing" double-checked locking was not one of the goals of the new memory model effort. (However, the new semantics of volatile allow one of the commonly proposed alternatives to double-checked locking to work correctly, although the technique is still discouraged.)

Related discussions:

I can understand why it is broken without the volatile fix. but I don't know why it is still discouraged even after the fix. I noticed some disagreement in one of the discussions. but if it is really as the reference suggested ? what could be the reason this fixed version is still discouraged?

Community
  • 1
  • 1
zinking
  • 5,561
  • 5
  • 49
  • 81
  • 2
    Because there are better options? For the singleton pattern, using an enum is the recommended way for example. – assylias Aug 17 '16 at 16:18
  • 2
    Because it's very easy to get it wrong, very hard to get it and maintaining right, for basically no advantage over easier, less subtle techniques achieving the same goal. – JB Nizet Aug 17 '16 at 16:24
  • I agree with both previous comments, but would add that is hard to *tell* when you've got it wrong. ie it may "look right" to you, but actually be wrong. Better to go with a pattern that is known to work than try to walk the long road already travelled by yourself. – Bohemian Aug 17 '16 at 17:47
  • 1
    Could be because synchronized is good enough for most cases, and likely even better than DCL. HotSpot adjusts lock's behavior at runtime based on contention. It [used to default to biased locking](https://openjdk.java.net/jeps/374), now it defaults to CAS style lightweight locking, promoting to heavyweight actual thread suspension if necessary [as explained here](https://www.alibabacloud.com/blog/lets-talk-about-several-of-the-jvm-level-locks-in-java_596090). – Vsevolod Golovanov Jul 22 '21 at 15:59

1 Answers1

0

So first of all: with the new Java MM the double-checked locking idiom is not broken anymore. So you can safely use it in Java.

There are also situations where all other alternatives cannot be used (like enums or static initialization). For example, if you need access to a non-static reference in order to construct the singleton.

So it is safe to use as long as you have completely understood the idiom.

Jan Schaefer
  • 1,882
  • 1
  • 18
  • 23