为什么Java的SimpleDateFormat不是线程安全的? [英] Why is Java's SimpleDateFormat not thread-safe?

查看:133
本文介绍了为什么Java的SimpleDateFormat不是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉代码示例为什么SimpleDateFormat不是线程安全的。这堂课有什么问题?
是SimpleDateFormat格式函数的问题吗?
请给出一个在课堂上演示此错误的代码。



FastDateFormat是线程安全的。为什么?
与SimpleDateFormat和FastDateFormat有什么区别?



请用解释此问题的代码解释一下?

解决方案

SimpleDateFormat 将中间结果存储在实例字段中。因此,如果一个实例被两个线程使用,它们就会混淆对方的结果。



查看源代码显示有一个日历实例字段,由 DateFormat / SimpleDateFormat <上的操作使用/ p>

例如 parse(..)调用 calendar.clear()最初然后 calendar.add(..)。如果另一个线程在第一次调用完成之前调用 parse(..),它将清除日历,但是另一个调用将期望它将填充中间结果计算。



在没有交易线程安全的情况下重用日期格式的一种方法是将它们放在 ThreadLocal 中 - 一些图书馆这样做。如果你需要在一个线程中多次使用相同的格式。但是如果你使用的是servlet容器(有一个线程池),请记得在完成后清理本地的线程。



说实话,我不知道理解为什么他们需要实例字段,但这就是它的方式。您也可以使用 joda-time DateTimeFormat 是线程安全的。


Please tell with a code example why is SimpleDateFormat not threadsafe. What is the problem in this class? Is The problem with format function of SimpleDateFormat? Please give a code which demonstrates this fault in class.

FastDateFormat is threadsafe. Why? what is the difference b/w the SimpleDateFormat and FastDateFormat?

Please explain with a code which demonstrates this issue?

解决方案

SimpleDateFormat stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.

Looking at the source code reveals that there is a Calendar instance field, which is used by operations on DateFormat / SimpleDateFormat

For example parse(..) calls calendar.clear() initially and then calendar.add(..). If another thread invokes parse(..) before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with intermediate results of the calculation.

One way to reuse date formats without trading thread-safety is to put them in a ThreadLocal - some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.

To be honest, I don't understand why they need the instance field, but that's the way it is. You can also use joda-time DateTimeFormat which is threadsafe.

这篇关于为什么Java的SimpleDateFormat不是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆