java.text.SimpleDateFormat不是线程安全的

Synchronization Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally 

上面的行在SimpleDateFormat类的JavaDoc中提到。

这是否意味着我们不应该将SimpleDateFormat对象创建为Static。

如果我们将其创建为静态,那么无论我们在何处使用此对象,我们都需要将其保存在Synchronized Block中。

是SimpleDateFormat不是线程安全的,并且在解析它应该以同步方式访问的日期时也建议使用它。

 public Date convertStringToDate(String dateString) throws ParseException { Date result; synchronized(df) { result = df.parse(dateString); } return result; } 

另一种方法是http://code.google.com/p/safe-simple-date-format/downloads/list

确实如此。 您可以在StackOverflow上找到有关此问题的问题。 我用它来声明它为ThreadLocal

 private static final ThreadLocal THREAD_LOCAL_DATEFORMAT = new ThreadLocal() { protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; 

并在代码中:

 DateFormat df = THREAD_LOCAL_DATEFORMAT.get(); 

多数民众赞成。 来自Apache Commons Lang的FastDateFormat是一个很好的线程安全替代品。

从版本3.2开始,它支持解析,在3.2之前只进行格式化。