Call to method of static java.text.DateFormat not

2019-01-18 01:01发布

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);

标签: java static
8条回答
迷人小祖宗
2楼-- · 2019-01-18 01:39

I'm not sure if FindBugs is complaining about this, but one problem I see with your code is that you're defining TODAY as a class level (static), constant (final) variable. This communicates the intent that you want TODAY to never change (I don't believe this is the case, since java.util.Dates are mutable, but that's another story).

Think about what happens if you application runs for multiple days? TODAY (unless you update it) will be referencing the day the application was started, not the current date. Are you sure this is what you meant?

This may not be a bug in your code at all, but the intent is not clear, and I believe that may be what FindBugs is complaining about.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-18 01:39

An alternative that not has been mentioned is using ThreadLocal. See http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html for more info + performance comparison between the 3 options:

  • Creating an instance each time
  • Synchronising access
  • Using ThreadLocal

Example of using ThreadLocal:

private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("yyMMdd");
    }
};

Usage:

DATE_FORMAT.get().format( TODAY )
查看更多
Root(大扎)
4楼-- · 2019-01-18 01:45

It's not thread-safe, for one thing.

查看更多
Bombasti
5楼-- · 2019-01-18 01:50

You can get this to go away by wrapping all the references to the DateFormat in a synchronize block - just make sure all calls are wrapped in the same synchronize object!

查看更多
倾城 Initia
6楼-- · 2019-01-18 01:51

I assume this is because format is not thread-safe?

(I have not seen what findbugs complain about, can you provide the warning text?)

查看更多
smile是对你的礼貌
7楼-- · 2019-01-18 01:53

Are you sure it's not

private static final DateFormat yymmdd = new SimpleDateFormat("yyMMdd"); 

? That's what the error message indicates.

I think what it aims at is the fact that DateFormat is not thread safe, so having an instance as a static field indicates potential race conditions.

查看更多
登录 后发表回答