3

From the release notes, checkstyle removed the Double-Checked locking check.

I'm having a hard time understanding why. They replied this not only in the release notes but also in the issue tracker:

Removed the DoubleCheckedLocking check, as in Java 5 (and beyond), using the volatile keyword addresses the issue.

I'm assuming that, if checkstyle is removing this warning, it's because it is no longer helpful. That is, either the error won't happen anymore or another warning does the job. But

I can't see why such error won't happen anymore in Java 5, or how it is complemented by another warning. Could someone care to explain?

EDIT: I understand how adding the volatile keyword solves the issue. My concern is: isn't this warning still worth it somehow? I'm thinking on the case when the programmer uses the aforementioned locking pattern, but forgets to declare the variable volatile. Shouldn't checkstyle still warn about it?

Thiago
  • 2,238
  • 4
  • 29
  • 42
  • possible duplicate of [is "Double-Checked Locking is Broken" a java-only thing?](http://stackoverflow.com/questions/5958767/is-double-checked-locking-is-broken-a-java-only-thing) See also: http://www.ibm.com/developerworks/library/j-jtp03304/ – assylias Nov 20 '12 at 17:51
  • In particular: "*[prior to Java 5] while reads and writes of volatile variables could not be reordered with reads and writes of other volatile variables, they could still be reordered with reads and writes of nonvolatile variables*". – assylias Nov 20 '12 at 17:54

1 Answers1

8

The description pretty much explains the decision. As of Java 1.5 you can use volatile instance variable. It will correctly handle memory visibility issues and using double checked locking is no longer a bug.

It doesn't mean that using volatile is the solution. But in 1.5 Java Memory Model was redefined, making volatile sufficient.

See also

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 2
    Shouldn't checkstyle still warn you if you forget to declare the instance variable as volatile in case one uses such pattern? In other words, if you forget to declare the variable as volatile, isn't it worthy of a checkstyle warning anymore? – Thiago Nov 20 '12 at 18:16
  • @Thiago Yes, I believe this was not a good decision, but maybe there was simply no time to fix the check, so they decided to take it out temporarily. A new check would be needed for Java 5 and upwards (which is by now pretty much standard). – barfuin Nov 27 '12 at 09:56