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.需要的时候创建局部变量


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM