SimpleDateFormat Not Thread-Safe

這幾天在看 SimpleDateFormat 的用法時,

因為之前認為此物件只是做 Formatter 用,
就把它宣告成 static final 的 instance variable 來處理 Date 的格式.
完全沒想到在 multi threads 的情況下會出現問題.
其實在 JDK 中也有提到
"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 externally."
1.每次使用就 new SimpleDateFormat 一次;;
2.使用 synchronized 把 parse 或 format 的這一段包起來 (如果把 SimpleDateFormat 宣告成 static 時)
synchronized(simpleDateFromat) {
   String val = simpleDateFromat.format(new Date());
但應該是會有 Performance issue…
其它的就是建立一個 user-defined date formatter class, 然後在 parse, format methods 加上 synchronized,
或使用別人寫的 date formatter (ex: org.apache.commons.lang.time.FastDateFormat => 只有支援 format, 所以也不適用…)
或使用 ThreadLocal (不過會有memroy leak的問題, For WebContainer…)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s