Weird NumberFormatException Using SimpleDateFormat

SimpleDateFormat from JDK is not thread-safe, so be careful when it is used in a concurrent environment. Although it is clearly stated in the Javadoc of the API that it’s not synchronized, I think many would not notice it until we encounter problems caused by the issue.

Let’s see an example first.

Above program starts 5 threads, each of which parses a date string using shared SimpleDateFormat. Run above program several times, very likely you will get one of the below unexpected results or exceptions.

  1. Exception in thread "Thread-4" java.lang.NumberFormatException: For input string: ""
  2. Exception in thread "Thread-1" java.lang.NumberFormatException: multiple points
  3. Thu Jun 27 10:33:09 CST 2024
  4. Exception in thread "Thread-2" java.lang.NumberFormatException: empty String
  5. Fri Jun 27 10:33:09 CST 2200
  6. ......

As shown above, sometimes you get an exception (mostly the NumberFormatException: For input string: ""), sometimes it just gives incorrect values.

To avoid the problem, you can create a SimpleDateFormat each time when you parse a string. Of course, this is not efficient enough. If you want a more superior solution, you can use ThreadLocal to make sure each thread has its own copy, you probably also want to cache the created instances. To see the details of this solution, you can refer to up Jesper’s blog post, it also provides a performance comparison of several solutions.