Wednesday, December 12, 2007

Building thread-safe code with SimpleDateFormat


The scenario is simple.

Each resource in JeromeDL has an upload and update dates; each is stored in a very simple format yyyyMMdd, e.g., 20071212 (for today).

From time to time - we need to get a Java Date object of out this information.

What we do?

Use SimpleDateFormat object parse and format date, getting it back and forth between Java and RDF.

Simple, right?

Yes, as long as your read the whole documentation of the SimpleDateFormat class - to discover that the objects are not synchronized. In other words - what will run on a standalone application with one processor - might very easily break when you try it on a server with multiple processors (or Intel HT).

Luckily, the solution is equally simple - use synchronized block, and you’re done.