Skip to content
Advertisement

“Java DateFormat is not threadsafe” what does this leads to?

Everybody cautions regarding Java DateFormat not being thread safe and I understand the concept theoretically.

But I’m not able to visualize what actual issues we can face due to this. Say, I’ve a DateFormat field in a class and the same is used in different methods in the class (formatting dates) in a multi-threaded environment.

Will this cause:

  • any exception like format exception
  • discrepancy in data
  • any other issue?

Also, please explain why.

Advertisement

Answer

Let’s try it out.

Here is a program in which multiple threads use a shared SimpleDateFormat.

Program:

JavaScript

Run this a few times and you will see:

Exceptions:

Here are a few examples:

1.

JavaScript

2.

JavaScript

3.

JavaScript

Incorrect Results:

JavaScript

Correct Results:

JavaScript

Another approach to safely use DateFormats in a multi-threaded environment is to use a ThreadLocal variable to hold the DateFormat object, which means that each thread will have its own copy and doesn’t need to wait for other threads to release it. This is how:

JavaScript

Here is a good post with more details.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement