[Codenarc-user] CodeNarc rule for double-checked locking
Brought to you by:
chrismair
From: Chris M. <chr...@ea...> - 2010-09-06 01:01:20
|
I am considering working on a CodeNarc rule for detecting the Double-Checked Locking pattern. It would probably have to be pretty narrow/specific, along the lines of the DCL rules in both PMD <http://pmd.sourceforge.net/rules/basic.html#DoubleCheckedLocking> and Checkstyle, essentially only flagging code that follows the pattern: private Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) helper = new Helper(); } } return helper; } I realize that the memory model in Java 1.5 means that if you declare helper as volatile, that this idiom will actually work, as discussed in http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html and other places. So, I may be able to craft the rule so that it only flags DCL if the variable is NOT volatile. Then again, some have argued that even so, that idiom is usually unnecessary and confusing, preferring the Initialization On Demand Holder idiom or just plain synchronization, so there might be value in a rule that always flags DCL (or makes that configurable). I was just wondering whether anyone had any opinion on that, one way or the other. Thanks. Chris |