zoukankan      html  css  js  c++  java
  • SimpleDateFormat的使用问题

    今天对过去的代码进行重构,因为使用静态方法调用的原因,使用了一个静态的SimpleDateFormat,结果FindBug报错了,查看了一下,说是使用了静态的SimpleDateFormat对象。

    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说明,说以前发现是因为在使用这个静态对象的时候,如果服务器过载,很容易爆出这个bug,进而发现SimpleDateFormat非线程安全。
    原来的写法如下:

    public class ControllerHelper {
       /**
        * Date format
        */
       private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
       ...
    
       public String someMethod() {
          return DATE_FORMAT.format(new Date());
       }
    }

    既然此种情况对象无法服用,就使用多创建对象的方法来解决吧。

    public class ControllerHelper {
       /**
        * Date format
        */
       private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
       public String someMethod() {
          return new SimpleDateFormat(DATE_FORMAT).format(new Date());
       }
    }

    自此,findbug不在报错了

  • 相关阅读:
    HtmlParser 2.0 中文乱码问题
    关于phpmyadmin中添加外键的做法
    jquery easyui Tab 引入页面的问题
    Python用户交互input()和print()
    Python运算符
    计算机硬件基础知识(五)操作系统发展史
    Python学习0304作业
    Python的垃圾回收机制
    Python的两种运行程序的方式
    Python发展史和编程语言的分类
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461608.html
Copyright © 2011-2022 走看看