SimpleDateFormat 你用了吗?
突然感觉有必要写一些日志了,很多知识点不温习就忘了,但是我今天不是忘了,是得到了一个新的教训。
项目上线了,出现了很多BUG,没办法只能一个一个的解决。本以为不会出现错误的方法确让我栽了个跟头,悲哀谈不上,单是有必要记录一下给自己个教训。
SimpleDateFormat 这个类估计写JAVA程序的都用过,但是真的都了解吗,我看不一定,和我一样只知道用不去了解的人还是有很多的,对此我希望能简单的提醒大家一下,这个类不是线程安全的(以前没有想到过这个问题!!!)。
SimpleDateFormat的Jdk 的Source,有这么一段注释,说明它不是线程安全的。
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
再看一下Sun自己的网站上。在sun的bug database中
Bug ID: 4228335 讲的就是这个问题。
SimpleDateFormat is not threadsafe (one more try)
其中有这么几段话值得关注:
1、 Aside from the obvious, there are two reasons why this fix should be made:
- The documentation for DateFormat states that a DateFormat object should be used
multiple times, implying that construction is expensive. Furthermore,
no mention is made of SimpleDateFormat's lack of thread-safety.
Since for most applications the date formats remain constant,
it is very easy to conclude that DateFormats should be application globals.
But SimpleDateFormat produces incorrect results when used in this way.
- Bug 4101500, a similar problem with NumberFormat, was fixed.
建议修改这个问题,而且NumberFormat已经修改,解决了这个问题。
2、Use of a cloned Calendar object in format(), as suggested in JDC comments,
slows down the execution 30-50%. And it potentially affects footprint because
of cloned objects. Another approach would be to have a Calendar instance per
thread. However, this approach will cause problems at the API semantic level due
to the get/setCalendar methods.
这一段解释了为什么没修改这个问题,一个是保持API不变,另一个是因为Clone比new慢,会损失效率
具体 clone 和 new 这两个哪个效率更高一些,自己动手去网上查一下吧!此类的文章页很多!