SimpleDateFormat 你使用了嗎?

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 這兩個哪個效率更高一些,自己動手去網上查一下吧!此類的文章頁很多!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章