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

  • 相关阅读:
    找零钱「Usaco2006 Dec」
    才艺表演「Usaco2018 Open」
    潜入行动「JSOI2018」
    任务安排「SDOI2012」
    BZOJ2298: [HAOI2011]problem a
    JZOJ 5818
    JZOJ 3493
    JZOJ 3470
    JZOJ 5781
    JZOJ 5778
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461608.html
Copyright © 2011-2022 走看看