Must-share information (formatted with Markdown):
- which versions are you using (SonarQube - Version 6.7.6 (build 38781) )
- what are you trying to achieve - Trying to catch static fields with the rule “Non-thread-safe fields should not be static”
- what have you tried so far to achieve this - Created static fields in the java source code
This rule is catching if i declare any classes from Java Library like SimpleDateFormat, but not catching if i declare one of my source code Java Class as static. What should i do to catch these?
Welcome to the community!
6.7.6 is past EOL. This is relevant to your question because we upgrade analyzers with each new SonarQube release, and its quite possible that current versions have fixed this False Negative.
So, I urge you to upgrade at your earliest convenience:
6.7.6 -> 7.9.3 (current LTS) -> 8.4.1 (current version)
And come back to us if the problem persists.
The rule you’re talking about is about classes that are known to cause problems when used across threads. Specifically it is about the four classes mentioned in the rule description. It is not meant to warn about the use of static fields in general, only ones containing instances of those classes.
Thank you Ann and Sebastian. So, this rule can’t be applied to the non-thread safe classes from my source code? I mean if i use an instance of any non-thread-safe class reference as static… this rule won’t catch and warn me(even after upgrading to latest sonar version)?. If this rule won’t help me, can you please let me know some other rule which i can use for this purpose?
I’m sorry, but we don’t have a rule that does what you want. Detecting whether a user-defined class is thread safe or not is not something that’s within the scope of our analyses and a rule that would complain about all classes would be too noisy for most users.
If you need a rule like this, you may want to look into defining a custom rule that fits your needs.
Thank you Sebastian. Is there anyway that i can look at the source code of this rule, so that i will have an idea how to write my custom rule. I know you have already shared a link but i need exact rule that can be applied to user defined classes. This would be a great help.
You can find the code for the rule here.