本文介绍了调用静态java.text.DateFormat的方法不可取吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我收到查找错误错误 - 调用静态java.text.DateFormat 的方法和我不知道为什么它不是以下是好的/可取的。I am receiving a Find Bugs error - call to method of static java.text.DateFormat andI 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不是线程安全的,这意味着它们维护国家的内部代表。如果多个线程同时访问同一个实例,在静态上下文中使用它们会产生一些非常奇怪的错误。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:public class MyClass { private String fileName; public MyClass() { final Date today = Calendar.getInstance().getTime(); final DateFormat yymmdd = new SimpleDateFormat("yyMMdd"); this.fileName = "file_" + yymmdd.format(TODAY); } ...}如果你需要要在多个地方使用格式化程序,您可能只需要创建模式 static final 并在需要时创建一个新的本地 DateFormat :And if you need to use the formatter in multiple places, you might just make the pattern static final and create a new local DateFormat when needed:public class MyClass { private static final String FILENAME_DATE_PATTERN = "yyMMdd"; public void myMethod() { final DateFormat format = new SimpleDateFormat(FILENAME_DATE_PATTERN); // do some formatting }} FindBugs文档:正如JavaDoc所述,对于多线程使用,DateFormats本身就是不安全的。检测器找到了一个调用的DateFormat实例,它通过静态字段获得了。这个看起来很可疑。有关这方面的更多信息,请参阅Sun Bug#6231579和Sun Bug#6178997。For more information on this see Sun Bug #6231579 and Sun Bug #6178997.并且日期格式的javadoc 建议: Jack Leow的回答也有关于静态使用TODAY的语义的一个好点。Jack Leow's answer also has a good point about the semantics of your static use of "TODAY".另外,我实际上已经看到这种情况发生在高流量的生产环境中,一开始调试是一件非常令人困惑的事情;所以根据我的经验,FindBugs警告实际上是一个有用的建议(不像其他一些静态分析规则,有时看起来很挑剔)。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). 这篇关于调用静态java.text.DateFormat的方法不可取吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-04 21:43