Tuesday, April 21, 2015

Java 8 : Date and Time - Part I


Wikipedia defines Time as:

"Time is a measure in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.Time is often referred to as the fourth dimension, along with the three spatial dimensions."

Since Time is a natural concept, in an ideal world, dealing with it should be simple, but unfortunately it is not the case and we humans made it more complex by introducing different time zones and day light saving.

As a programmer, we want that programming languages immune us from these complexity and being a Java programmer, we have similar expectations from Java. Java tried to overcome these complexities in its first two editions of Date and Time API, but failed measurably. A simple google will give you numerous posts criticizing Java for this. Few years back, I was introduced to Joda-Time library that provide APIs that help you to work with Time with ease.

In its latest edition (Java 8), in its third attempt, finally Java brought this change that we all were looking for long. With its new APIs, it is no more require to use either third party APIs or create several utility classes/methods to deal with date and time.  This new API is heavily inspired by Joda-Time library.

Java 8 - Date and Time API

New API defines classes to map the concepts of Instant, Duration, Period, Time (Local and Zoned). All the classes are immutable and thread safe. Official java.time package summary offers a great detail on the different concepts and worth a visit.

Instant and Duration:

In Java, an Instant represents a point on the time line. An origin, called the epoch, is arbitrarily set at midnight of January 1, 1970 GMT. This is the same convention used in the Unix/POSIX time. Starting from that origin, time is measured in 86,400 seconds per day, forwards and backwards, in nanosecond precision. Instant is essentially a timestamp.

Duration is amount of time between two instants. Both instants and duration are scalar values, that mean time zone or day light saving doesn't affect them.

Getting Current Instant:

Instant instant = Instant.now();

Duration between two instants:
        Instant startInstant = Instant.now();
        Instant endInstant = Instant.now();
        Duration duration = Duration.between(startInstant,endInstant);

Adding time to a duration is pretty straight forward:

    public void editDuration(Duration duration){
        // Enhance Duration by 5 minutes
        Duration enhanceDurationByMinute = duration.plusMinutes(5);
        //Enhance Duration by 2 Days, 5 hours, 6 minutes, 
        // 10 Seconds, 200 milliseconds and 788 nanoseconds
        Duration enchanced = duration.plusDays(2).plusHours(5).plusMinutes(6)

Important point to note here is, since Duration is an immutable, every time you call a plusXXX() method, it returns a new object of Duration.

Duration stores time in two parts, seconds and nano seconds and provide two methods to get these parts. It provides methods to get total time in different units viz. milliseconds, minutes, hours.

Getting Duration in human readable form:

    public static void getDurationBetweenTwoInstants(){
        Logger logger = Logger.getGlobal();
        Instant startInstant = Instant.now();
        for(int i = 0; i < Integer.MAX_VALUE; i++){
            //Do nothing
        Instant endInstant = Instant.now();
        Duration duration = Duration.between(startInstant, endInstant);
        logger.log(INFO, "" + duration);
        duration = duration.plusHours(5).plusMinutes(8).plusSeconds(2)
        logger.log(INFO, "Total Time :" + duration);

        logger.log(INFO, "NanoSecond Part of Total Time: " 
                                    +  duration.getNano());
        logger.log(INFO,"Seconds Part of Total Time: " 
                                    +  duration.getSeconds());

        logger.log(INFO,"Total time in Nano : " +  duration.toNanos());
        logger.log(INFO,"Total time in Millis : " +  duration.toMillis());
        logger.log(INFO,"Total time in Minutes : " +  duration.toMinutes());
        logger.log(INFO,"Total time in Hours : " +  duration.toHours());

A sample Output of above program looks like:

INFO: Time in looping: PT0.006S
INFO: Total Time :PT5H8M2.240000234S
INFO: NanoSecond Part of Total Time: 240000234
INFO: Seconds Part of Total Time: 18482
INFO: Total time in Nano : 18482240000234
INFO: Total time in Millis : 18482240
INFO: Total time in Minutes : 308
INFO: Total time in Hours : 5

Similar methods exists for subtraction as well.


Instants and Duration is the basis of new Date and Time API. But as you can see, both the APIs are not that useful from human being interaction and for that there are other APIs that relates to Periods, Local and Zoned Date/Time. I will discuss about them in my next post.

Friday, June 15, 2012

Exploring Java 7 : Try-with-resources

Try-with-Resource is new featured added in Java 7. Personally, I like this feature very much, as it helps to reduce a lot of boiler plate code.

Consider a scenario, where we have to release a system resource, like JDBC Connection or File Stream. Prior to Java 7, it meant that developer has to write a lot of boiler plate code to release that resource. In order to ensure releasing of resource in all the situations, one has to use finally block as well for exception cases. Consider following example, written with Java 6:

String readFirstLine(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null)
Clearly, one has to write almost 4-5 lines for closing each resource. Now, what Java 7 did is that it made the process of closing resource automatic.

In Java 7, a resource is defined as "An object of type java.lang.AutoCloseable.". This AutoCloseable interface has a single method close() and this method is invoked automatically when a resource is used with try block. See below example:
String readFirst(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();

Impressive!!! Isn't it? We have reduced boiler plate code drastically and there is no scope of accidentally forgetting to close a resource. All resource will be freed automatically.

Few points to remember:
  • A resource must be declared in parenthesis, immediately after try block.
  • A Try-with-Resource can have catch and finally blocks, just as with try block.
  • There can be multiple resources in a single Try-with-Resource block
  • public void readEmployees(Connection con){
      String sql = "Select * from Employee";
      try (Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql)){
       //Work with Statement and ResultSet   
      } catch (SQLException sqe) {
  • In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration

Friday, June 1, 2012

Interface or Abstract Class

What is the difference between an Abstract Class and an Interface?
Well, isn't it an interesting question or for few, a foolish question?

For a number of Java newbies, the only difference between two is, "You can't have method body in Interface.". Well, I would say that it is technically (Implementation vise) correct, but doesn't reflect the concept.

Abstract Class
An abstract class, is the most generalized form of an Entity hierarchy (In Java, a Class is an entity), such that it doesn't represent a real entity on its own, but provides a basis on which real entities can be build within that hierarchy. An abstract class provides a default behavior and also provide abstract behavior (Operations that must be override by the real classes).

An interface, on the other hand is a contract that states that you have to agree to provide following operations if you agree to abide by me, i.e. an entity that agrees to abide by the contract of interface, will have to provide the behavior (operations) declared in interface.

Interface or Abstract Class
Next question is when to use abstract class and when use an Interface? Though it many a depends on requirements as well, but I follow a thumb rule,
  • If I have to build a class hierarchy, I should consider generalization. Many a time I will reach to most crude form of generalization, i.e. at an abstract level. I would declare abstract methods and will also define common behavior for few of the methods. This would be my abstract class.
  • On the other hand, if I want to expose a particular behavior to the client, then I would define an interface. 

Further, I would suggest that one should go through different Java APIs, and spend some time understanding when and why they used interface or abstract class. Java APIs are excellent source for learning on building design blocks for any OOPs language.