(转载)SimpleDateFormat的使用问题

(转载)https://blog.csdn.net/ethanwhite/article/details/47131623

今天对过去的代码进行重构,因为使用静态方法调用的原因,使用了一个静态的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不在报错了

猜你喜欢

转载自blog.csdn.net/zhuhai__yizhi/article/details/82462535