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不在报错了

  • 相关阅读:
    tableView小细节
    iOS5 切换中文键盘时覆盖输入框的解决方案
    NSBundle读取txt文件,图片,plist
    iOS OC 字符串处理
    图片拉伸 几种方式
    UIAlertView小结
    新来报道
    VC6.0之Debug调试总结
    关于C++中的临时对象问题
    与临时对象的斗争(下)
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461608.html
Copyright © 2011-2022 走看看