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