FindBug:Call to static DateFormat
2015-07-29 18:11
381 查看
今天在重构代码的过程中碰到了一个问题。使用SimpleDateFormat的问题。
本人今天写了一个类,主要是提供很多静态的方法由其他接口调用,过程中多个方法使用到了日期的格式化,所以我讲SimpleDateFormat声明为了static 变量,结果在使用findBug插件对文件进行检索的时候,碰到了问题。
STCAL: Call to static DateFormat (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. The detector has found a call to an instance of DateFormat that has been obtained via a static field. This looks suspicous.
For more information on this see Sun Bug #6231579 and Sun Bug #6178997.
Sun早已发布了这个bug,是由于使用的SimpleDateFormat非线程安全造成的。
原来因为采用上面的写法,有的时候可能会造成Bug。 Sun公司的bug记录中也有提到,当服务超载的情况下,就会出现bug。
现在将其改为下面的写法
现在采用这种写法,每次都会生成新的SimpleDateFormat对象,就不会出现错了。使用FindBug检查一遍,发现问题解决。
本人今天写了一个类,主要是提供很多静态的方法由其他接口调用,过程中多个方法使用到了日期的格式化,所以我讲SimpleDateFormat声明为了static 变量,结果在使用findBug插件对文件进行检索的时候,碰到了问题。
STCAL: Call to static DateFormat (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. The detector has found a call to an instance of DateFormat that has been obtained via a static field. This looks suspicous.
For more information on this see Sun Bug #6231579 and Sun Bug #6178997.
Sun早已发布了这个bug,是由于使用的SimpleDateFormat非线程安全造成的。
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); public String someMethod() { return DATE_FORMAT.format(new Date()); }
原来因为采用上面的写法,有的时候可能会造成Bug。 Sun公司的bug记录中也有提到,当服务超载的情况下,就会出现bug。
现在将其改为下面的写法
private static final String DATE_FORMAT = "yyyy-MM-dd"; public String someMethod() { return new SimpleDateFormat(DATE_FORMAT).format(new Date()); }
现在采用这种写法,每次都会生成新的SimpleDateFormat对象,就不会出现错了。使用FindBug检查一遍,发现问题解决。
相关文章推荐
- JAVA基础点汇总(四)
- FindBug:Call to static DateFormat
- VC 窗口出现白屏闪烁的解决办法
- javascript深入理解js闭包
- 利用javascript实现文本的自动输出
- 前端开发面试题
- cocos2dx中的三种缓存
- python设计模式之责任链模式
- ScrollView与ListView共存代码
- 使用eclipse搭建maven多module项目
- linux CentOS6.5安装mysql-5.6.4
- 不再是学生了,做好码农
- python写入xml文件的方法
- html及css学习笔记_2_html基本结构
- Incorrect string value: '' for column '' at row 1
- ActionManager 源码阅读
- IOS--开发基础知识
- IOS--文件管理NSFileManager
- Web_CGI_Ser交互流程
- 继承