java.text.SimpleDateFormat is not thread safe

本日、しばらくハマった問題。SimpleDateFormatインスタンスをスレッド間で共有させてたためにエラーや、意味不明な値が返るなどなど。

原因わかるまでの要領が悪かったなァ。。公式docは丁寧に読んどかないとだ。

同期

日付フォーマットは同期化されません。スレッドごとに別のフォーマットインスタンスを作成することをお勧めします。複数のスレッドがフォーマットに並行してアクセスする場合は、外部的に同期化する必要があります。 http://docs.oracle.com/javase/jp/7/api/java/text/SimpleDateFormat.html

ローカルで都度インスタンス生成するように変更して解決。 joda-time も検討しようかな。

Does it support multi-threading?

Every public class in Joda-Time is documented as being thread-safe or not. Joda-Time makes heavy use of the immutability design pattern, and all immutable classes in Joda-Time are thread-safe. Many mutable classes whose instances are not likely to be shared are not thread-safe, and are documented as such.

The most common multi-threading mistake made by Java programmers is in the use of SimpleDateFormat. Calling its format method on a shared instance by concurrent threads can produce bizarre results. All of Joda-Time's formatting classes are thread-safe and immutable.

http://www.joda.org/joda-time/faq.html

(訳)Joda-Time のすべてのパブリッククラスはスレッドセーフか否かドキュメントに付されています。 Joda-Timeはイミュータブルデザインパターンを多用しており、Joda-Timeのイミュータブルなクラスはスレッドセーフです。多くのミュータブルなクラスは、そのインスタンスは共有されることも少なく、スレッドセーフでは有りませんし、そのようにドキュメントに書かれています。

Javaプログラミングでのマルチスレッド実装において最もよくあるミスは、SimpleDataFoamatの使用時に見られます。並列スレッド間で共有されたインスタンスに対してfoamatメソッドを呼ぶと、奇妙な結果が帰ってきます。Joda-Timeのフォーマットクラスはすべてスレッドセーフかつイミュータブルです。