"Calendars" and "DateFormats" should not be static

参见:Call to method of static java.text.DateFormat not advisable?

 
级别:bug, multi-threading

Not all classes in the standard Java library were written to be thread-safe. Using them in a multi-threaded manner is highly likely to cause data problems or exceptions at runtime. 
This rule raises an issue when an instance of Calendar, DateFormat, javax.xml.xpath.XPath, or javax.xml.validation.SchemaFactory is marked static.

Noncompliant Code Example:

public class MyClass {
  static private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");  // Noncompliant
  static private Calendar calendar = Calendar.getInstance();  // Noncompliant

Compliant Solution:

public class MyClass {
  private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");
  private Calendar calendar = Calendar.getInstance();

后面这种solution也不能保证安全性,要保证完全安全性只能是使用局部变量进行栈封闭

原文地址:https://www.cnblogs.com/drizzlewithwind/p/6425495.html