Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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.

    Immutable Objects

    What is Immutable Object
    An immutable object is something whose state can't be change after there creation, e.g. String objects. Once you have created a String object, you can't alter this.

    Creating an Immutable object's class
    Creating an immutable object's class can be tricky. Minimal requirement to create an immutable object's class is, make class and every member variable, "final".

    public final class SimpleImmutableClass {
     final int intVal = 5;
     final String sampleString = "Hello";
     final Integer intObj = Integer.valueOf(10);
    }

    SimpleImmutableClass is a class of mutable object, one can't change its state, once object is created. But it is too simple case. In real world situation is far more complex, you will rarely find such a simple class that has only primitive or immutable members (actually String and Integer classes are classes for immutable objects, provided by JDK API stack).

    Consider following example, that has mutable objects as members, though every member is final, private and has only getters (to access) and no setters, but still do you think that it is a class that can produce immutable objects.
    public final class NotAnImmutableClass{
    private final ArrayList<String> sampleList = new ArrayList<String>();
     private final Date today = new Date();
     
     public ArrayList<String> getSampleList() {
      return sampleList;
     }
     public Date getToday() {
      return today;
     }
    }

    What do you think about above class, is it really an Immutable object's class? Unfortunately, a big NO. At first it seems like it is an immutable object's class, after all, it is a final class, every variable is final and private and to give more assurance, it doesn't contain any "setter" method. Some may give me a good fight arguing about immutability of the objects of this class.
    But then comes the villain, the very basic of Java, the "Reference".  Consider the following listing:

    class PokeIntoSoCalledImmutableClass {
    public void poke(){
      NotAnImmutableClass notAnImmutableClass = new NotAnImmutableClass();
      List<String> samples = notAnImmutableClass.getSampleList();
      Date d = notAnImmutableClass.getToday();
      samples.add("Poked String");
      d.setYear(111);  
      System.out.println(notAnImmutableClass.getSampleList().size());
      System.out.println(notAnImmutableClass.getToday());
     }
     
    }
    
    What do you think, the method  poke() would print? Do you think it would print "0" and "Sun Jun 05 00:00:00 IST 2010"?  Answer is a big NO!!!

    So, here comes another rule for a class whose objects to be immutable, either it should not have any mutable field (as in our case) or it should not publish (expose) its mutable members.

    But again question is, what if we have to expose mutable objects and still we need that our class's objects are immutable? Well answer is simple but tricky. USE CLONING!!!! If exposed object contains only immutable objects or primitive types, use shallow copy, otherwise use deep copy.
    Correct way to implement Immutable class:

    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class AnImmutableClass {
     private final ArrayList<String> sampleList = new ArrayList<String>();
     private final Date today = new Date(110,5,5);
     
     public ArrayList<String> getSampleList() {
      ArrayList<String> returnList = new ArrayList<String>();
      for(String s : sampleList){   
       returnList.add(s);
      }
      return returnList;
     }
     public Date getToday() {
      return (Date)today.clone();
     }
     
     public static void main(String[] args) {
      PokeIntoSoCalledImmutableClass pokeClass = new PokeIntoSoCalledImmutableClass();
      pokeClass.poke();
     }
     
    }
    
    class PokeIntoSoCalledImmutableClass {
     public void poke(){
      AnImmutableClass anImmutableClass = new AnImmutableClass();
      List<String> samples = anImmutableClass.getSampleList();
      Date d = anImmutableClass.getToday();
      samples.add("Poked String");
      d.setYear(111);  
      System.out.println(anImmutableClass.getSampleList().size());
      System.out.println(anImmutableClass.getToday());
     }
     
    }
    

    I here conclude with set of rules to make a class whose objects are immutable:
    • Must be final
    • Only final members should be exposed to outer world
    • Exposed members should be immutable
    • If it is require to expose mutable members, then use shallow or deep cloning while exposing them


    FOR-EACH Loop

    Add to Technorati Favorites
    Java 5 introduced a lot of new features which were being sought for quite long. It is a total overhaul of the language. Though these features have minimum or no effect on produced bytecode, Bytecode remains unchanged.

    FOR-EACH LOOP:

    It is irritating. I need to traverse all elements in a data structure and for this I have to write a conditional loop as I do in C language. Come on, it is a high level language, it should have natural processing. Most natural way should be,

    "FOR EACH ELEMENT IN DATA STRUCTURE, DO SOMETHING"

    And it is what, the Sun engineers did. They introduced a "FOR EACH" loop for traversing all the elements in a data structure but with a condition, data structure should implement "Iterable" interface.

    PS : There is one exception to it. Arrays can also be iterated in this way.

    Syntax for "FOR EACH" loop is:

    For(Element e : DATA STRUCTURE (of type element) ){

    //do something with e

    }


    Let's illustrate it with some examples.

    Let's define a Java Collection and traverse it. All collections in Java are of type Collection and Collection Interface (java.util.Collection) extends the "Iterable" interface. Hence, all collections in Java are candidate for "FOR EACH LOOP".

    //Code
    
    //Define a Collection
    
    Collection<String> collection = new ArrayList<String>();
    
    //Add elements in collection
    
    collection.add("FIRST");
    
    collection.add("SECOND");
    
    collection.add("THIRD"); 
    //Traverse using For each loop 
    for(String s : collection) 
    { 
    //Print the element 
    System.out.println(s); 
    } 
    
    //Code End.

    Well, Java specification states that any class that implements Iterable interface, is a candidate of "For Each" loop. It means that we can also take advantage of this feature in user defined data structures as well. I googled, but did not find any example for this implementation. So, I am posting an implementation of user defined class that take advantage of this feature.

    I have created a class for Linear Link list.
    //Code Start
    import java.util.Iterator;
    /**
     * This class is Java implementation of LinearLinkList. 
     * This class demonstrates the implementation of 
     * for each loop. A data structure must
     * implement Iterable interface in order
     *  to use the for each loop
     * feature of Java 1.5
     *  
     * @author Vineet 
     * @param < T >
     */
    public class LinearLinkList< T > implements Iterable< T > {
     /**
      * It represents the header of LinkList. 
      * It is the first node of LinkList.
      */
     private Node< T > head = new Node< T >();
     /**
      * Size of LinkList.
      */
     private int size = 0;
    
    
     /**
      * Constructs empty link list.
      */
     public LinearLinkList() {
     }
    
    
     /**
      * Evaluates the size of link list.
      * 
      * @return size of link list.
      */
     public int size() {
      return size;
     }
    
    
     /**
      * Adds an element at the end of list. 
      * If it is empty list, then element is
      * set in head node.
      * 
      * @param element
      */
     public void add(T element) {
      // If it is empty list, set element in header node.
      if (size() == 0) {
       head.element = element;
      }
      // Else, create a node with this element 
      //and add at the end of list.
      else {
       Node< T > node = new Node< T >();
       node.element = element;
       Node< T > temp = head;
       while (temp.nextNode != null) {
        temp = temp.nextNode;
       }
       temp.nextNode = node;
       temp = null;
      }
      size++;
     }
    
    
     /**
      * String representation of Link List.
      */
     @Override
     public String toString() {
      StringBuilder str = new StringBuilder();
      Iterator< T > itr = this.iterator();
      while (itr.hasNext()) {
       str.append(itr.next().toString() + ",");
      }
      str.deleteCharAt(str.lastIndexOf(","));
    
    
      return str.toString();
     }
    
    
     @Override
     public int hashCode() {
      int hash = (int) (31 * Math.random() + 61 * Math.random());
      return hash;
     }
    
    
     /**
      * Returns iterator for this list. It enables it to 
      * be candidate of for each loop.
      */
     @Override
     public Iterator< T > iterator() {
      // TODO Auto-generated method stub
      return new Itr();
     }
    
    
     /**
      * Finds the element at index position in list.
      * 
      * @param index
      *            position of element to be sought.
      * @return Element at position index
      */
     public T get(int index) {
      Node< T > temp = head;
      while (index > 1) {
       temp = temp.nextNode;
       index--;
      }
      return temp.element;
     }
    
    
     /**
      * This class is iterator for this Link List.
      * It enables the navigation of link list.
      * 
      * @author Vineet
      * 
      */
     private class Itr implements Iterator< T > {
      private int cursor = 0;
      private Node< T > temp = head;
    
    
      @Override
      public boolean hasNext() {
       return cursor++ < size();
      }
    
    
      @Override
      public T next() {
       T element = temp.element;
       temp = temp.nextNode;
       return element;
      }
    
    
      @Override
      public void remove() {
      }
    
    
     }
    
    
     private static class Node< T > {
    
    
      T element;
      Node< T > nextNode;
    
    
     }
    
    
     public static void main(String[] args) {
    
    
      LinearLinkList< String > test = new LinearLinkList< String >();
      test.add("First");
      test.add("Second");
      test.add("Third");
      test.add("Fourth");
      test.add("Fifth");
    
    
      // Now it will work with For Each loop
      for (String s : test) {
       System.out.println(s);
      }
      System.out.println(test);
     }
    
    
    }
    
    
    
    //Code Ends