Java 8 : Date and Time - Part I

Preface

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)
                .plusSeconds(10).plusMillis(200).plusNanos(788);
        
    }

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)
                        .plusMillis(234).plusNanos(234);
        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.

Conclusion

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.

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)
    br.close();
  }
 }
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) {
       sqe.printStackTrace();
      }
     }
  • In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration

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).

Interface
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.

Singleton Pattern: Am I implementing it Correctly? - Part II

In my last post, I discussed implementation of Singleton Pattern in a Single Threaded Environment. There was a very good discussion on whether about very existence of this pattern as well. Actually it is an ever going debate, few people think that it is an anti pattern and few think it is a simple solution of a common problem.

My intent of this post (and previous also) is to discuss on how to implement it, rather than whether to use it!!! So, let's start discussing Singleton Pattern in a Multi-threaded environment.

Singleton Pattern in Multi-Thread environment:

We have seen using static factory to implement Singleton Pattern in a single thread environment and also discussed problems associated with it. When in Multi-threaded environment, there are other problems as well.

What will happen if two threads simultaneously try to access static factory method (getInstance() method)? It will result in two instance of class, though we required only one instance. Clearly, singleton pattern is broken.

This problem is not only associated with Java, but also to other languages as well, like C++.  A naive solution is to synchronize the static factory method, so that at any given time, only one thread can execute getInstance() method. So, even if we ignore the problems arising from reflection (see previous post) and want to use singleton pattern, then it would be used in this way:
public class SingletonInMultiThread {
 private static SingletonInMultiThread singletonInstance; 
 private SingletonInMultiThread(){} 
 public SingletonInMultiThread getInstance(){
  if(singletonInstance == null) singletonInstance = new SingletonInMultiThread();
  return singletonInstance;
 } 
}

Well, there is no problem (other than we discussed for reflection) in above code, but there is an overhead of synchronization every time, as we need synchronization only at the time of creation.There are two ways to resolve this problem.

One is to instantiate the variable at the time of declaration and remove synchronization from static factory method.To resolve this synchronization
public class SingletonInMultiThread {
 private static SingletonInMultiThread singletonInstance = new SingletonInMultiThread(); 
 private SingletonInMultiThread(){} 
 public SingletonInMultiThread getInstance(){  
  return singletonInstance;
 } 
}
Another solution is to use infamous Double Checked Locking (Just google it and can find thousands of articles saying same thing), but it is also broken, see DCL.

But, Good News is that with Java 5 and using volatile for instance variable, you can seal this DCL broking :)

So, we have seen how we can use Singleton Pattern in a multi-thread environment, but with above discussion, there are still few issues:
  • We ignore the breaking of Singleton Pattern by reflection
  • It is quite cumbersome to implement Singleton Pattern in multi-threaded environment

As I said in previous post, starting from Java 5, a much easier way to control number of instances is to use ENUM. With all the advantages we discussed earlier, it is threadsafe!!!

Conclusion:
Whenever you need to control number of instances of a type, it is better to consider Enum. Enums are special classes whose number of instances are controlled by JVM itself!!!

Singleton Pattern: Am I implementing it Correctly? - Part I

Novice way to implement a Singleton:
I believe everyone starts (and even continues to do so) implementing Singleton pattern in following fashion:
package com.singleton;

public class SimpleSingleton {
 private static SimpleSingleton simpleSingleton;

 private SimpleSingleton() {
 };

 public static SimpleSingleton getInstance() {
  if (simpleSingleton == null)
   simpleSingleton = new SimpleSingleton();
  return simpleSingleton;
 }
}

Do you find any problem in it?
Well, I have!!! The contract of Singleton class can be broken. 
Let's discuss Singleton pattern in Simple Threaded environment and then in next post I will discuss this pattern in Multithreaded environment.

In a Single Threaded Environment:
Do you remember the double edge sword in Java, "REFLECTION"?
With the help of reflection, one can very easily breach the singleton contract for above class and create as many instance as he wants. Let's consider following three statements:
//Get Private Constructor
  Constructor pvtConstructor = Class.forName(
    "com.singleton.SimpleSingleton").getDeclaredConstructors()[0];
  
  //Set its access control
  pvtConstructor.setAccessible(true);
  
  //Invoke Private Constructor
  SimpleSingleton notSingleton = (SimpleSingleton) pvtConstructor
    .newInstance(null);

Here is a summary what is happening in above statements:
  • First statement retrieves the Constructor object for private constructor of SimpleSingleton class.
  • Since the constructor retrieved is a private one, we need to set its accessibility to true.
  • Last statement invokes the private constructor and create a new instance of SimpleSingleton class.
Clearly, we have breached the contract of Singleton class. So, how to overcome this problem?
Well, prior to Java 1.5, there was no way (at least in my knowledge, but Java Universe is so big that I can't say with 100% surity :) ) to save a singleton class from Reflection mechanism. In Java 1.5, a new kind of classes were introduced, "Enum".


Unlike Classes, an Enum has fix number of objects and since this restriction is implemented by JVM's native libraries, hence it is unbreakable. Let's see an example:
public enum SampleEnum {
 ONLY_INSTANCE();
}

Now let's try to create an object of SampleEnum using reflection:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class enumTest {
 public static void main(String[] args) throws ClassNotFoundException,
   IllegalArgumentException, SecurityException,
   InstantiationException, IllegalAccessException,
   InvocationTargetException {
  Constructor c1 = Class.forName("SampleEnum").getDeclaredConstructors()[0];
  c1.setAccessible(true);
  SampleEnum e1 = (SampleEnum) c1.newInstance(null);
 }
}
On running this example, it will throw an exception:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects
 at java.lang.reflect.Constructor.newInstance(Constructor.java:511)
 at enumTest.main(enumTest.java:11)
Clearly, you can't create an object of Enum type.


Hence, we can conclude that best way to implement a Singleton pattern is by using Enum. It is simple, straightforward and unbreakable.


Further, in my next post, I will discuss about Singleton pattern in Multithreaded environment.

Runtime.addShutdownHook()

Preface:
Every Java Program can attach a shutdown hook to JVM, i.e. piece of instructions that JVM should execute before going down.

Problem:
A program may require to execute some pieces of instructions when application goes down. An application may go down because of several reasons:
  • Because all of its threads have completed execution
  • Because of call to System.exit()
  • Because user hit CNTRL-C
  • System level shutdown or User Log-Off
Few scenarios where this requirement fits are:
  • Saving application state, e.g. when you exits from most of the IDEs, they remember the last view
  • Closing some database connections
  • Send a message to System Administrator that application is shutting down.
Solution:
Shutdown Hook comes to rescue in all such scenarios. Application attach a shutdown hook to thereself, that JVM runs when application goes down.

Concept at Abstract level:
Write all the instructions(java code) in a thread's run method and call java.lang.Runtime.addShutdownHook(Thread t). This method will then register this thread with JVM's shutdown hook. At the time of shutting down, JVM will run these hooks in parallel (Thread will be started only at the time of shut down by JVM itself).

Sample code:
public class AddShutdownHookSample {
 public void attachShutDownHook(){
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("Inside Add Shutdown Hook");
   }
  });
  System.out.println("Shut Down Hook Attached.");
 }
public static void main(String[] args) {
  AddShutdownHookSample sample = new AddShutdownHookSample();
  sample.attachShutDownHook();
  System.out.println("Last instruction of Program....");
  System.exit(0);
 }}

Output is:
Shut Down Hook Attached.
Last instruction of Program....
Inside Add Shutdown Hook
I think now I am clear with on how to use addShutDownHook. One can attach as many shutdown hooks as he wants, but beware, these hooks will be run in parallel, so keep concurrency in mind, so that no deadlock or race condition exists.

Are you going to implement it in your application:
There are few more things that should be kept in mind while using this method:
  • Number of Shutdown hooks: There is no limitations on number of shutdown hooks, one can attach as many shutdown hooks as he wants. See the modified version of run method above,
    public void attachShutDownHook(){  
      for(int i =0; i<10;i++){
       Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {    
         System.out.println("Inside Add Shutdown Hook : " + Thread.currentThread().getName()) ;
        }
       }); 
      }

    See, we have attached ten shutdown hooks here.
  • When to attach Shutdown hook: Anytime!!! One can attach a shutdown hook at any instance of time, but before JVM starts shutting down. If one tries to register a shutdown hook after JVM starts shutting down, then it will throw an IllegalStateException with message, "Shutdown in progress" 
  • Attaching same hook again: One can't attach same hook again and if it happens, it will throw  IllegalArgumentException with message "Hook previously registered
  • De-Register a Hook: One can de-register a hook as well by simply calling method Runtime.removeShutdownHook(Thread hook)
    PS: Most of the time, shutdown hooks are registered using anonymous inner classes, but since we don't have any reference available for them, we should not use anonymous inner classes for hooks that we may de-register, because we need to pass there reference in removeShutdownHook(Thread hook) method.
  • Keep an eye on Concurrency: In case one have attached more than one shutdown hook, then they will run in parallel and hence pron to all issues related to threads, e.g. deadlocks or race conditions. Java Doc for the method also state that:
    /**
      * A <i>shutdown hook</i> is simply an initialized but unstarted thread.
      * When the virtual machine begins its shutdown sequence it will start all
      * registered shutdown hooks in some unspecified order and let them run
      * concurrently. When all the hooks have finished it will then run all
      * uninvoked finalizers if finalization-on-exit has been enabled. Finally,
      * the virtual machine will halt. Note that daemon threads will continue to
      * run during the shutdown sequence, as will non-daemon threads if shutdown
      * was initiated by invoking the <tt>{@link #exit exit}</tt> method.
      */

  • Reliability of Shutdown Hook: JVM tries his best to execute shutdown hooks at the time of going down, but it can't be guranteed, e.g. when JVM is killed using -kill command on Linux or Terminate Process on windows, then JVM exits instantly or it crashes because of some native code invocation.
  • Keep an eye on Time Consumption by hooks: One of the important thing to note is that shutdown hooks should not be time consuming. Consider the scenario when user logs off from OS, then OS assign very limited time to gracefully shutdown, hence in such scenarios JVM can forcefully exit.

    Conclusion:
    Runtime.addShutdownHook(Thread hook) can be a very handy tool, especially in big applications like server implementations as it provide a generic mechanism for graceful exit from JVM. Still, it should be used with care.

    References: 

    Remote debugging in Java

    Buzz Word: Remote Debugging
    Consider a scenario where you can't run the application in your development environment, e.g. say your application can run only on a server machine (because it is dependent on some third party interface that are not accessible in your development machine) and you have to resolve a problem (bug). What you can do?

    The solution is Remote debugging. Remote debugging is debugging an application by connecting the remotely running application with your development environment ( i.e. you can say to connect with code in your IDE).

    How it works : Basic concept
    Remote debugging feature is provided by Java specification itself. Java provides this feature using listener binding mechanism. Basic concept is pretty simple and straightforward:
    • Application to be debugged would attach a socket to itself and then would listen debug instructions on that socket.
    • Debugger would bind itself to that socket and then send instructions on that socket.
    Running an application in debug mode:
    As I said earlier, for remote debugging, you need to run that application in debug mode. To run an application in debug mode requires to provide specific jvm arguments to "java" command.

    JVM arguments for DEBUGGING:
    • For JVMs prior to 1.5:
      One need to supply two arguments, -Xdebug and -Xrunjdwp. -Xdebug tells JVM to run the application in debug mode, while -Xrunjdwp is used to supply debug parameters (It can also be used in JVM 1.5 or 1.6 as well)
      e.g. -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
    • For JVMs 1.5 and 1.6:
      Debug library is passed as -agentlib argument, along with debug paramters. Native library name for debugging is jdwp, so one need to supply -agentlib:jdwp along with debug paramters.
      e.g. -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n
    Detail of debug parameters:
    • Name: help
      Is Optional : Yes
      Default Value: N/A. This parameter doesn't have any value at all.
      Description: It prints all the available options on the console and exits the JVM.
      Example: java -agentlib:jdwp=help

    • Name: transport
      Is Optional: No (It is a required field)
      Default Value: No default value specified in specifications. Totally depends upon native lib provided by JVM implementation.
      Description: Transport protocol implementation used for communication between debugger and application. Sun JVM ships two implementations, Socket Transport and Shared Memory Transport. Value for Socket Transport is "dt_socket", while that of Shared Memory Transport is "dt_shmem".
      Shared Memory is available only on Microsoft Windows.
    • Name: server
      Is Optional: Yes
      Default Value: n
      Description: Tells whether JVM will be used as Server or as client in reference to JVM-Debugger communication. If JVM will act as server, then debugger will attach itself to this JVM, otherwise if JVM will act as a client, then it will attach itself to debugger.
    • Name: address
      Is Optional: Optional when JVM acts as server and Required when JVM acts as client.
      Description: Specifies the socket address.
      If JVM is server (i.e. server argument is set to 'y'): Then JVM listens the debugger at this socket. If address is not specified, then JVM picks any of available socket, starts listening on this socket and prints its address on console.
      If JVM is client (i.e. server argument is set to 'n'): JVM attaches itself to this address to connect itself to debugger.
    • Name: timeout
      Is Optional: Yes
      Description: As its name signifies, it is the wait time for JVM. If JVM is server, then JVM will wait for "timeout" amount of time for debugger to attach to its socket and if JVM is client, then it will exit if fail to attach to debugger in timeout time.
    • Name: suspend
      Is Optional: yes
      Default Value: y
      Description: Tells JVM to suspend the invocation of application(s) until the debugger and JVM are attached together.

    Apart these there are launch, onthrow, onuncaught options as well, details of which can be find at JPDA. But these options are seldom used.


    Now, lets take simple example to debug a program using eclipse.

    Steps:
    • Select from eclipse menu, Run->Debug Configuration, It will open Debug Configuration setup.
    • On Debug configuration window, create a new "Remote Java Application" configuration.
    • Select the project to be debugged and provide a Name.
    • Select connection type, Socket Attach or Socket Listen. Select Socket Attach, if you want to attach the debugger to application, i.e. application is running in Server mode. On the other hand, select Socket Listen, in case you want debugger to listen for JVM to connect, i.e. JVM is running in client mode and debugger is running as server.
    • If JVM to be run in Server mode, then first start JVM in debug mode and then start the newly created debugger, 
    • And if Debugger to be run in Server mode, then first start the debugger and then start JVM.
    Debugging in Action:








    In this way one can debug any java application using any standard java debugger.

    Later in some post I will try to cover "How to debug" for different kind of java application, e.g. debugging application running in Tomcat or Jboss, debugging a JWS and like that.