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 ?
Not thread safe − java. util. Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable and does not have setter methods.
The standard alternate is using the Calendar Object. Calendar has one dangerous point (for the unwary) and that is the after / before methods. They take an Object but will only handle Calendar Objects correctly. Be sure to read the Javadoc for these methods closely before using them.
util. Date has some serious design flows, from the day it was introduced. Many of its methods were deprecated since Java 1.1 and ported to (abstract) java. util.
util. Date (just Date from now on) is a terrible type, which explains why so much of it was deprecated in Java 1.1 (but is still being used, unfortunately). Design flaws include: Its name is misleading: it doesn't represent a Date , it represents an instant in time.
In this order, from best to worst:
Not use it at all, check out Java 8's new Date and Time API.
Not use it at all, check out jodatime
Not use it at all, use AtomicLong
or immutable primitive long
with volatile
to represent epoch time
Encapsulate it. Always return defensive copy of Date
, never a reference to internal object
Synchronize on Date
instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With