6

When Instant was introduced with JSR-310, convenience methods were added to perform conversion between Date and Instant:

Date input = new Date();
Instant instant = input.toInstant();
Date output = Date.from(instant);

I wonder why it was chosen to be this way instead of, let's say, having Date output = instant.toDate(). My guess is that it was intended to avoid making Instant dependent on Date. Is this right?

But to me it is somehow strange that you make the new class independent of the already existing one, and make the old one dependent on the newly introduce one. Is this made so because of an expected deprecation of Date or is there any other reason?

1 Answers1

8

Problems with Date:

  • It is a mutable object
  • It is not thread-safe
  • cost of using it in a thread-safe manner (synchronized) is expensive

Instant on the other hand is designed to be thread-safe and immutable. Making the object Immutable is by itself already a simple and inexpensive way of guaranteeing thread-safety. The Javadoc for Instant states:

Implementation Requirements:
This class is immutable and thread-safe.

Now if you want to do something like Instant t = Instant.from(new Date()), that means the implementers of the API would have to introduce synchronization to guarantee the thread-safe access of the Date object.

I suspect that they wanted to simply have a clean break with the old ways, and avoid introducing any explicit synchronized methods. Introducing synchronized methods would have suggested that it is ok to use them. While it might be useful to have, it would be setting a bad precedent.

Instead they have chosen to keep the conversion of Date to Instant within the Date API, which does not document any thread-safety. Safe assumption would be that it is up to the user to synchronize access to the Date Object first if required to do so.

YoYo
  • 584