2

SonarQube 5.5 (with the sonar-java-plugin-3.13.1.jar plugin) reports an issue on this code:

public class TimeA { public static final SimpleDateFormat DATE_FORMATTER; static { SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); df.setTimeZone(TimeZone.getTimeZone("GMT")); DATE_FORMATTER=df; } } 

The error message is Make "DATE_FORMATTER" an instance variable.

How can I avoid this SonarQube issue?

2
  • 1
    This post explains what an instance variable is: stackoverflow.com/questions/16686488/… Commented Jul 27, 2017 at 7:28
  • The versions of SonarQube and SonarJava plugin you are using are quite old. You should update to the more recent versions. Commented Jul 27, 2017 at 9:24

1 Answer 1

7

In the above class, SonarQube is trying to say that DATE_FORMATTER does not need to be static if it is not used by any static method.

In fact, SimpleDateFormat should not be an instance variable as well, as it's not thread safe (explained here). If multiple threads are accessing methods of TimeA class simultaneously then it will lead to incorrect result.

If the format is same then you can declare it as a final String and create SimpleDateFormat instances locally, e.g.:

public final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; public void someMethod(){ SimpleDateFormat df=new SimpleDateFormat(DATE_FORMAT); df.setTimeZone(TimeZone.getTimeZone("GMT")); //Further processing } 
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, Got it. Thank you for your help.
For the logs, if you have performance constraints, you can also consider using ThreadLocal to store one date format per thread.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.