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?

  • 2
    see Joda Time vs Java Time. In brief, old-fashioned Java time API turned out poor design choice and designers of new API dropped it completely, without trying to polish the turd – gnat Jan 5 '16 at 11:37
  • @gnat I'm not asking about when to use one or the other, or about old Java Time at all. – mark951131b Jan 5 '16 at 11:56
  • 6
    "make the new class independent of the already existing one" - this is the case, one doesn't make good API dependent on a poor one – gnat Jan 5 '16 at 12:01
  • "Is this made so because of an expected deprecation of Date" - I suspect this is, maybe, eventually on the table. In which case you wouldn't want to touch the new API when getting rid of the old one, no. – Clockwork-Muse Jan 8 '16 at 10:59
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.