How to make java.util.Date thread-safe

You may use the long value (milliseconds since Epoch) instead of a Date instance. Assigning it will be an atomic operation and it would always be coherent.

But your problem maybe isn't on the Date value itself but on the whole algorithm, meaning the real answer would be based on your real problem.

Here's a example of buggy operation in a multithread context :

long time;
void add(long duration) {
   time += duration; 
}

The problem here is that you may have two additions in parallel resulting in only one effective addition, because time += duration isn't atomic (it's really time=time+duration).

Using a long instead of a mutable object isn't enough. In this case you could solve the problem by setting the function as synchronized but other cases could be more tricky.


The simplest solution is to never modify a Date and never share it. i.e. Only use Date for local variables.

You can use JodaTime as it has immutable date objects.


In this order, from best to worst:

  1. Not use it at all, check out Java 8's new Date and Time API.

  2. Not use it at all, check out jodatime

  3. Not use it at all, use AtomicLong or immutable primitive long with volatile to represent epoch time

  4. Encapsulate it. Always return defensive copy of Date, never a reference to internal object

  5. Synchronize on Date instance.