Why is Java's SimpleDateFormat not thread

This question already has an answer here:

  • “Java DateFormat is not threadsafe” what does this leads to? 10 answers


  • SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.

    From the JavaDoc ,

    But 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 .

    To make the SimpleDateFormat class thread-safe, look at the following approaches :

  • Create a new SimpleDateFormat instance each time you need to use one. Although this is thread safe, it is the slowest possible approach.
  • Use synchronization. This is a bad idea because you should never choke-point your threads on a server.
  • Use a ThreadLocal. This is the fastest approach of the 3 (see http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html).

  • Java 8中的DateTimeFormatterSimpleDateFormat不可变且线程安全的替代方案。

    链接地址: http://www.djcxy.com/p/36638.html

    上一篇: 将以下字符串解析为year,month,date,hourOfDay,minute,second

    下一篇: 为什么Java的SimpleDateFormat不是线程