peter
peter

Reputation: 8473

How to make java.util.Date thread-safe

As far as i know that java.util.Date is mutable, so it's not thread-safe if multiple threads tried to accessing and modifying it. How do we use client-side locking or composition (wrapper) to make it thread-safe ?

Upvotes: 20

Views: 15368

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340873

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

  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.

Upvotes: 37

Denys Séguret
Denys Séguret

Reputation: 382264

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.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533660

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.

Upvotes: 2

Adam Sznajder
Adam Sznajder

Reputation: 9216

There is no simple solution to create a thread-safe wrapper of Date class. The best way is to synchronize all usages of it's objects by using synchronized blocks.

Upvotes: -1

Related Questions