SimpleDateFormat线程不安全原因

  • parse 方法为什么不线程安全

1.有一个共享变量calendar,而这个共享变量的访问没有做到线程安全

2.parse方法生成CalendarBuilder,然后通过CalendarBuilder 设值到calendar,最后calendar.getTime();

clipboard

3.api方法说明 This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information.

  • format方法为什么不线程安全

1.有一个共享变量calendar,而这个共享变量的访问没有做到线程安全

2.当使用format方法时,实际是给calent共享变量设置date值,然后调用subFormat将date转化成字符串

clipboard[1]

--------------------

clipboard[2]

-------------------

clipboard[3]

  • 解决方案

1.创建一个共享的SimpleDateFormat实例变量,但是在使用的时候,需要对这个变量进行同步

2.使用ThreadLocal为每个线程都创建一个线程独享SimpleDateFormat变量

3.需要的时候创建局部变量

posted @ 2017-02-21 20:19  lion85  阅读(7848)  评论(0编辑  收藏  举报