I am receiving a Find Bugs error - call to method of static java.text.DateFormat and I don't know the reason why it's not good / advisable to be doing these things below.
private static final Date TODAY = Calendar.getInstance().getTime();
private static final DateFormat yymmdd = new SimpleDateFormat("yyMMdd");
private String fileName = "file_" + yymmdd.format(TODAY);
DateFormats are not thread-safe, meaning that they maintain an internal representation of state. Using them in a static context can yield some pretty strange bugs if multiple threads access the same instance simultaneously.
My suggestion would be to make your variables local to where you're using them instead of making them static properties of the class. It looks like you might be doing this when you're initializing the class, so you could do this in the constructor:
And if you need to use the formatter in multiple places, you might just make the pattern
static final
and create a new localDateFormat
when needed:The FindBugs documentation for the issue says:
And the javadoc for DateFormat suggests:
Jack Leow's answer also has a good point about the semantics of your static use of "TODAY".
As an aside, I've actually seen this happen in a high-traffic production environment, and it's a very confusing thing to debug at first; so in my experience the FindBugs warning is actually a useful suggestion (unlike some other static analysis rules, which sometimes seem to be nitpicky).
Commons Lang has a FastDateFormat object that is thread safe. It only does formatting though, not parsing.
If you can use commons-lang this might work well for you.