Monday, September 30, 2019

Overview of Java 8’s new Date-Time API

Motivation for the major Date and Time API upgrade in Java 8

Date and Time is one area where until Java 7 programmers had to do make do with a poorly designed API. Not only were the commonly used java.util.Date(from JDK 1) and java.util.Calendar(from JDK 1.1) classes mutable, they were non-thread safe as well.

Several design decisions around these classes were not up to the otherwise high JDK design standards. For example – Date’s year offset started from the year 1900, the value contained in the Date object was not really a ‘date’ but was an offset from the Java epoch in milliseconds, the month index of Calendar starts from 0 (instead of 1), and so on…

The primary class provided for date formatting, java.text.DateFormat, was not thread safe. As a result, two concurrent threads utilizing the same DateFormat instance could lead to corrupted results!

Over the years, the lack of a good quality Date and Time library in core JDK led to the popularity of non-JDK date-time libraries such as Joda-Time1.

Core Ideas behind the design of new Date-Time API in Java 8

Thread Safety: java.util.Date and java.util.DateTimeFormatter were not thread safe. In today’s parallel programming paradigms, these are performance disasters waiting to happen. Java 8’s Date-time classes have been defined as immutable by default. So, if you modify the date or time using any of the in-built library methods then what you get back is a new instance with new values, the old instance remains the same. Result – A siginificant boost for concurrent processing environments.
Domain-driven design: Domain-driven design refers to deriving the class design and interaction based on their actual usage in business systems. So, classes and their interactions and straightforward. For example: There is no need to create a date out of milliseconds from Java epoch if you do not really require that. Just use an instance of java.time.LocalDate instead.
In-built support for multiple calendar systems: Java 8 has significantly improved the handling of non-ISO 8601 calendar systems such as Japanese or Thai calenders. This should further improve the acceptability of the new date-time API for implementing non-standard chronology specific requirements.

No comments:

Post a Comment