One of the rule defined in the PMD rule set is: "Avoid using Volatile" which explains that "Use of modifier volatile is not recommended". This rule is mentioned under the Controversial Rule Set of PMD.
In my team, we have Sonar configured on various modules which indirectly has the rule set from PMD and hence any use of volatile pops as a critical warning.
Question is why are we using volatile?
The volatile keyword is used for boolean variables to control the state of the external session. This state is accessed across various threads and hence to know if the state is UP or DOWN, it is maintained as a boolean volatile variable, so that visibility is shared across multiple threads.
My question is how to fix this sonar warning?
One solution is to remove the rule from the rule set, which is not allowed because: firstly it is not recommended as these rules form the basic guidelines defined from PMD rule set and secondly the SONAR server in my organisation is a central server being used by all the teams. Hence is not allowed.
Another solution is to ignore the sonar warning by use of some annotation, which is again not recommended on basic rule set.
Can anyone suggest how can we fix this sonar warning in code?
Thanks in advance.
First off, this rule does not indicate a general problem in the code - volatile
is a perfectly fine keyword, and there is nothing wrong with it. That's why it's a controversial rule.
On the other hand, using it is indeed a bit of an advanced technique that requires you to know what you are doing. Situations exist where you would know that, let's say, the people who will maintain your code will not have sufficient Java knowledge. In such cases, the rule may make sense.
To satisfy the rule in your case, use AtomicBoolean.