Monday 12 November 2012

Copy lines command issue in eclipse


In Eclipse, the shortcut key to Copy lines is cntrl+alt+down but there is a problem with this shortcut key. Ctrl+alt+down turns the screen upside down in MS windows.
One way to handle this problem is to disable the hot keys from graphic options.

Right-click on your desktop screen and select Graphics options > hotkeys > Disable.

Copy lines command issue in eclipse
Disable screen rotation
Other way could be to change the Copy Lines command to some other shortkey already not used by Eclipse.

To do this, go to Window à Preferences
Copy lines command issue in eclipse
 Then go to General à Keys
Copy lines command issue in eclipse
Enter ‘Copy Lines’ in the text field
Copy lines command issue in eclipse
Click on Copy Lines and go to Bindings text field
Copy lines command issue in eclipse
Delete the contents of Bindings text field and press cntrl and down arrow and click OK button
In order to test  the command,  Go to any line or select any set of lines and press cntrl+down,  the lines will be copied. So instead of select, copy and paste simply select and duplicate without affecting the clipboard.
Copy lines command issue in eclipse


some of the directories, where the blogs can be searched are:-
http://www.directoryworld.net/


Spring singleton beans vs Singleton design pattern

Spring singleton beans vs Singleton design pattern


Singleton beans in Spring and classes based on Singleton design pattern are quite different.

Singleton pattern ensures that one and only one instance of a particular class will ever be created per classloader where as the scope of a Spring singleton bean is described as 'per container per bean'.
Singleton scope in Spring means that this bean will be instantiated only once by Spring. Spring container merely returns the same instance again and again for subsequent calls to get the bean.

The below example shows that repeated calls to get the ‘bloggerService’ bean returns the same bean again and again.

Defining a Singleton scoped bean in spring application context (appContext.xml)

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
   
    <bean id="bloggerService" 
               class="in.blogspot.javasampleprogram.BloggerService" />  
 </beans>  

 package in.blogspot.javasampleprogram;  
 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  

 class BloggerService   
 {  
      String blogName;  
      public String getBlogName() {  
           return blogName;  
      }  
      public void setBlogName(String blogName) {  
           this.blogName = blogName;  
      }  
 }  
 public class AppContextTest {  
      public static void main(String[] args) {  
           ApplicationContext context1 = new ClassPathXmlApplicationContext(
                  new String[] { "in/blogspot/javasampleprogram/appContext.xml" });  

           BloggerService custA = (BloggerService) context1.getBean("bloggerService");  
           custA.setBlogName("http://java-sample-program.blogspot.in/");  
           System.out.println("blog name: " + custA.getBlogName()); 
           
           // returns the same bean again  
           BloggerService custB = (BloggerService) context1.getBean("bloggerService");  
           System.out.println("blog name: " + custB.getBlogName());  
      }  
 }  
Console Output:
blog  name: http://java-sample-program.blogspot.in/

Now if we load the context again and then try to fetch the ‘bloggerService’ we will get a new bean. So even though the classloader of both context1 and context2 are same, there will be two separate BloggerService instances created by each context.
 package in.blogspot.javasampleprogram;  
 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  

 class BloggerService   
 {  
      String blogName;  
      public String getBlogName() {  
           return blogName;  
      }  
      public void setBlogName(String blogName) {  
           this.blogName = blogName;  
      }  
 }  
 public class AppContextTest {  
      public static void main(String[] args) {  
           ApplicationContext context1 = new ClassPathXmlApplicationContext(
                   new String[] { "in/blogspot/javasampleprogram/appContext.xml" });  
           
           BloggerService custA = (BloggerService) context1.getBean("bloggerService");  
           custA.setBlogName("http://java-sample-program.blogspot.in/");  
           System.out.println("blog name: " + custA.getBlogName()); 
  
           // returns the same bean again  
           BloggerService custB = (BloggerService) context1.getBean("bloggerService");  
           System.out.println("blog name: " + custB.getBlogName()); 
  
           // reloading the application context  
           ApplicationContext context2 = new ClassPathXmlApplicationContext(
                   new String[] { "in/blogspot/javasampleprogram/appContext.xml" });  
           
           custA = (BloggerService) context2.getBean("bloggerService");  
           System.out.println("blog name: " + custA.getBlogName()); // print null  
           
          // both context1 and context2 have same classloaders
          System.out.println("context1 classloader: "+context1.getClassLoader());
          System.out.println("context2 classloader: "+context2.getClassLoader());  
      }  
 }  
Console Output:
blog  name: null
context1 classloader: sun.misc.Launcher$AppClassLoader@53372a1a 
context2 classloader: sun.misc.Launcher$AppClassLoader@53372a1a

To read more about Spring bean scopes, please go through the below links:-
Spring Bean Scopes

To read more about Singleton design patterns:-

Saturday 10 November 2012

Cloning a Singleton class sample code

Cloning Singleton class
Cloning Singleton class
We can clone a Singleton class instance in a scenario where the singleton class extends from a class which implements Cloneable interface and provides implementation of clone() method. So now we can clone the instance by calling the Object class's clone() method on the singleton instance.
 class SingletonSuper implements Cloneable {  
         public Object clone() throws CloneNotSupportedException {  
                 return super.clone();  
         }  
 }  
 class Singleton extends SingletonSuper {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
 }  
 public class SingletonCloningTest  
 {  
         public static void main(String[] args) throws Exception  
         {  
                 System.out.println("Singleton Test!");  
                 System.out.println("Singleton Instance:"+Singleton.getInstance());  
                 System.out.println("Singleton clone:"+Singleton.getInstance().clone());  
         }  
 }  

Prevent cloning of singleton class


We can override the Object class's clone() method to throw the CloneNotSupportedException exception.
 class SingletonSuper implements Cloneable {  
         public Object clone() throws CloneNotSupportedException {  
                 return super.clone();  
         }  
 }  
 class Singleton extends SingletonSuper {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
          public Object clone() throws CloneNotSupportedException {  
                 // throw CloneNotSupportedException if someone tries to clone the singleton object  
                 throw new CloneNotSupportedException();  
          }  
 }  
 public class SingletonPreventCloningTest  
 {  
         public static void main(String[] args) throws Exception  
         {  
                 System.out.println("Singleton Test!");  
                 System.out.println("Singleton Instance:"+Singleton.getInstance());  
                 // will throw exception if clone method is called  
                 System.out.println("Singleton clone:"+Singleton.getInstance().clone());  
         }  
 }  

To read more about cloning, you can go through the following link:-
http://en.wikipedia.org/wiki/Clone_(Java_method)

20 java Singleton interview questions

20 singleton interview questions and answers
Q1: What is singleton design pattern?
Ans: Singleton design pattern ensures that at any time there can only be one instance of a class and provide a global point of access to it.

Q2: How will you implement singleton design pattern in java?
Ans: Singleton Pattern implementation:-
  1. Declare a default private constructor.
  2. Declare a private static variable to hold single instance of class.
  3. Declare a public static function that returns the single instance of class.
  4. Do “lazy initialization” in the accessor function.
Q3: Please write code to implement singleton design pattern in java
Ans:
 class Singleton {   
    // 1. Make all constructors private   
    private Singleton() {}   
    // 2.  Declare a private static variable to hold single instance of class   
    private static Singleton INSTANCE = null;   
    // 3.  Declare a public static function that returns the single instance of class    
    public static Singleton getInstance() {   
     // 4. Do "lazy initialization" in the accessor function.   
     if(INSTANCE == null) {   
      INSTANCE = new Singleton();   
     }   
     return INSTANCE;   
    }   
  }   
Q4: In which conditions the above code could lead to multiple instances?
Ans:
 public static Singleton getInstance() {   
   if(INSTANCE == null) { // 1   
     INSTANCE = new Singleton(); // 2   
   }   
   return INSTANCE; // 3   
  }   
If one thread enters getInstance() method and finds the INSTANCE to be null at step 1 and enters the IF block and before it can execute step 2 another thread enters the method and executes step 1 which will be true as the INSTANCE is still null,  then it might lead to a situation (Race condition) where both the threads executes step 2 and create two instances of the Singleton class.

Q5: Above question can be asked in a different way. How can Race condition happen in singleton design pattern in java?
Ans:
 public static Singleton getInstance() {   
   if(INSTANCE == null) { // 1   
     INSTANCE = new Singleton(); // 2   
   }   
   return INSTANCE; // 3   
  }   
If one thread enters getInstance() method and finds the INSTANCE to be null at step 1 and enters the IF block and before it can execute step 2 another thread enters the method and executes step 1 which will be true as the INSTANCE is still null,  then it might lead to a situation (Race condition) where both the threads executes step 2 and create two instances of the Singleton class.

Q6: Write code to recreate Race condition in singleton design pattern in java?
Ans:
 // Recreate threading issue during instantiation of Singleton class   
  class Singleton {   
      // 1. Make all constructors private   
      private Singleton() {}   
      // 2.  Declare a private static variable to hold single instance of class   
      private static Singleton INSTANCE = null;   
      // 3.  Declare a public static function that returns the single instance of class   
      public static Singleton getInstance() {   
        if(INSTANCE == null) {   
         try {   
          // If there is delay in creation of object then the threads might create multiple instances   
          Thread.sleep(10);   
          INSTANCE = new Singleton();   
         }   
         catch (InterruptedException ie) {   
           ie.printStackTrace();   
         }      
        }   
        return INSTANCE;   
       }   
  }   
  public class SingletonThreadingTest implements Runnable   
  {   
      public void run() {              
       System.out.println("Singleton instance id :"+Singleton.getInstance());   
      }   
      public static void main(String[] args)   
      {   
          System.out.println("Singleton Test!");   
          SingletonThreadingTest sei1 = new SingletonThreadingTest();   
          Thread thread1 = null;   
          for(int i=0; i< 2;i++) {   
              thread1 = new Thread(sei1);   
              // might create mutliple instances of Singleton class   
              thread1.start();   
          }   
      }   
  }   

 Q7: What is lazy initilization in Singleton design pattern?
 Ans: Lazy initialization happens when the initialization of the Singleton class instance is delayed till its static  getInstance() is called by any client program. And initialization of the Singleton class takes place inside the getInstance() method.

Q8: What is Eager initilization in Singleton design pattern?
Ans: Eager initilization happens when we eagerly initialize the private static variable to hold the single instance of the class at the time of its declaration.

Q9: Write code to implement eager initilization in Singleton design pattern?
Ans:
 // Eager instantiation of Singleton class   
  class Singleton {   
      // 1. Make all constructors private   
      private Singleton() {}   
      // 2.  Eagerly declare a private static variable to hold single instance of class   
      private static Singleton INSTANCE = new Singleton();   
      // 3.  Declare a public static function that returns the single instance of class   
      public static Singleton getInstance() {   
          return INSTANCE;   
      }   
  }   

Q10: How can we prevent race condition in singleton design pattern?
Ans: We can do it in three ways:-
1) By synchronizing the getInstance() method
2) By using eager initialization of instance
3) By using double checked locking method

Q11: What is the drawback of synchronizing the getInstance() method?
Ans: It will decrease the performance of a multithreaded system as only single thread can access the getInstance method at a time. Also synchronizing a method has its own overheads.

Q12: What can be the drawback of using eager initialization of instance?
Ans: If our application doesn't always creates and uses the singleton instance and overhead of creation of singleton instance is a major point of concern then we can avoid creating the instance of the class eagerly.

Q13: Explain double checked locking method?
Ans: Another way to prevent race condition issue is to use ‘Double checked Locking method’ to reduce the use of synchronization in getInstance() method. It is used to reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') without actually acquiring the lock. Only if the locking criterion check indicates that locking is required does the actual locking logic proceed. Its called double checked as we check the nullability of INSTANCE twice.

Q14: How will you implement double checked locking method?
Ans:
 // Double checked locking method   
  class Singleton {   
      // 1. Make all constructors private   
      private Singleton() {}   
      // 2.  volatile keyword ensures that multiple threads handle the INSTANCE variable   
      //   correctly when it is being initiaized.   
      private volatile static Singleton INSTANCE = null;   
      // 3.  method is not made synchronized   
      public static Singleton getInstance() {   
          // check that INSTANCE is initialized and if not then enter   
          // synchronized block   
          if(INSTANCE == null) {   
              synchronized(Singleton.class) {   
                  // inside the block check again for initialization   
                  if(INSTANCE == null) {   
                      INSTANCE = new Singleton();   
                  }   
              }   
          }   
          return INSTANCE;   
      }   
  }   

Q15: Can we get multiple instances of a singleton class by cloning?
Ans: Yes we can. It can happen in a scenario where the Singleton class extends from a class which implements Cloneable interface and provides implementation of clone() method. So now we can clone the instance by calling the Object class's clone() method on the singleton instance.


Q16: Show how we can create clone of a singleton class?
Ans:
 class SingletonSuper implements Cloneable {  
         public Object clone() throws CloneNotSupportedException {  
                 return super.clone();  
         }  
 }  
 class Singleton extends SingletonSuper {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
 }  
 public class SingletonCloningTest  
 {  
         public static void main(String[] args) throws Exception  
         {  
                 System.out.println("Singleton Test!");  
                 System.out.println("Singleton Instance:"+Singleton.getInstance());  
                 System.out.println("Singleton clone:"+Singleton.getInstance().clone());  
         }  
 }  

Q17: How can we prevent cloning in singleton?
Ans: We can override the Object class's clone() method to throw the CloneNotSupportedException exception.
 class SingletonSuper implements Cloneable {  
         public Object clone() throws CloneNotSupportedException {  
                 return super.clone();  
         }  
 }  
 class Singleton extends SingletonSuper {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
          public Object clone() throws CloneNotSupportedException {  
                 // throw CloneNotSupportedException if someone tries to clone the singleton object  
                 throw new CloneNotSupportedException();  
          }  
 }  
 public class SingletonPreventCloningTest  
 {  
         public static void main(String[] args) throws Exception  
         {  
                 System.out.println("Singleton Test!");  
                 System.out.println("Singleton Instance:"+Singleton.getInstance());  
                 // will throw exception if clone method is called  
                 System.out.println("Singleton clone:"+Singleton.getInstance().clone());  
         }  
 }  

Q18: Why do we have private constructors in singleton class?
Ans: A singleton can only have one instance. By making its constructors private we prevent creation of multiple instances of the class.

Q19: Give some use cases where we can use Singleton pattern?
Ans: Classes implementing Thread Pools, database Connection pools, caches, loggers etc are generally made Singleton so as to prevent any class from accidently creating multiple instances of such resource consuming classes.

Q20: If we load a spring application context twice how many instances of a singleton declared bean will there be in the JVM?
Ans: Two. As singleton beans are singletons at application context level.

Read more about Singleton pattern from the below link:-
http://en.wikipedia.org/wiki/Singleton_pattern

Singleton Design Pattern in Java

Singleton Design pattern in java

Singleton design pattern ensures that at any time there can only be one instance of a class and provide a global point of access to it.
Classes implementing Thread Pools, database Connection pools, caches, loggers etc are generally made Singleton so as to prevent any class from accidently creating multiple instances of such resource consuming classes.

Singleton design Pattern implementation:-
  1. Declare a default private constructor.
  2. Declare a private static variable to hold single instance of class.
  3. Declare a public static function that returns the single instance of class.
  4. Do “lazy initialization” in the accessor function. 

 class Singleton {  
     // 1. Make all constructors private  
     private Singleton() {}  
     // 2.   Declare a private static variable to hold single instance of class  
     private static Singleton INSTANCE = null;  
     // 3.   Declare a public static function that returns the single instance of class     
     public static Singleton getInstance() {  
       // 4. Do "lazy initialization" in the accessor function.  
       if(INSTANCE == null) {  
          INSTANCE = new Singleton();  
       }  
       return INSTANCE;  
     }  
 }  
 public class SingletonTest  
 {  
    public static void main(String[] args)  
    {  
       System.out.println("Singleton Test!");  
       // always return the same instance  
       System.out.println("Singleton instance id :"+Singleton.getInstance());  
       System.out.println("Singleton instance id :"+Singleton.getInstance());  
       System.out.println("Singleton instance id :"+Singleton.getInstance());  
       // can't create instance of Singleton class  
       //Singleton instance2 = new Singleton(); // Compilation Error  
    }  
 }  
Dealing with Multithreading in Singleton design pattern
 public static Singleton getInstance() {  
    if(INSTANCE == null) { // 1  
       INSTANCE = new Singleton(); // 2  
    }  
    return INSTANCE; // 3  
 }  
The above code can lead to creation of multiple instances in a multithreaded environment. Let’s take a closer look at the getInstance() method.

If one thread enters getInstance() method and finds the INSTANCE to be null at step 1 and enters the IF block and before it can execute step 2 another thread enters the method and executes step 1 which will be true as the INSTANCE is still null,  then it might lead to a situation (Race condition) where both the threads executes step 2 and create two instances of the Singleton class.

 // Recreate threading issue during instantiation of Singleton class  
 class Singleton {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = null;  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
             if(INSTANCE == null) {  
               try {  
                  // If there is delay in creation of object then the threads might create multiple instances  
                  Thread.sleep(10);  
                  INSTANCE = new Singleton();  
               }  
               catch (InterruptedException ie) {  
                   ie.printStackTrace();  
               }         
              }  
              return INSTANCE;  
           }  
 }  
 public class SingletonThreadingTest implements Runnable  
 {  
         public void run() {                        
           System.out.println("Singleton instance id :"+Singleton.getInstance());  
         }  
         public static void main(String[] args)  
         {  
                 System.out.println("Singleton Test!");  
                 SingletonThreadingTest sei1 = new SingletonThreadingTest();  
                 Thread thread1 = null;  
                 for(int i=0; i< 2;i++) {  
                         thread1 = new Thread(sei1);  
                         // might create mutliple instances of Singleton class  
                         thread1.start();  
                 }  
         }  
 }  

Eager instantiation in Singleton design pattern


We can prevent this issue by making the getInstance() method ‘synchronized’ but that will decrease the performance of your system as only single thread can access the getInstance method at a time. The other way could be to eagerly instantiate the INSTANCE variable.
Also if your application always creates and uses the singleton instance and overhead of creation of singleton instance is not a major point of concern then also we can create the instance of the class eagerly.

 // Eager instantiation of Singleton class  
 class Singleton {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Eagerly declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
 }  
 public class SingletonEagerInstantiationTest  
 {  
         public static void main(String[] args)  
         {  
                 System.out.println("Singleton Test!");  
                 // always return the same instance  
                 System.out.println("Singleton instance id :"+Singleton.getInstance());  
                 System.out.println("Singleton instance id :"+Singleton.getInstance());  
                 System.out.println("Singleton instance id :"+Singleton.getInstance());  
                 // can't create instance of Singleton class  
                 //Singleton instance2 = new Singleton(); // Compilation Error  
         }  
 }  
Double checked locking method
Another way to prevent multithreading issue is to use ‘Double checked Locking method’ to reduce the use of synchronization in getInstance() method. In this method the synchronized block is placed inside the first NULL check condition so the synchronized block will be executed only initially when the initialization of instance is not done. Its called double checked as we check the nullability of INSTANCE twice. 
 // Double checked locking method  
 class Singleton {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   volatile keyword ensures that multiple threads handle the INSTANCE variable  
          //     correctly when it is being initiaized.  
          private volatile static Singleton INSTANCE = null;  
          // 3.   method is not made synchronized  
          public static Singleton getInstance() {  
                  // check that INSTANCE is initialized and if not then enter  
                  // synchronized block  
                 if(INSTANCE == null) {  
                         synchronized(Singleton.class) {  
                                 // inside the block check again for initialization  
                                 if(INSTANCE == null) {  
                                         INSTANCE = new Singleton();  
                                 }  
                         }  
                 }  
                 return INSTANCE;  
          }  
 }  
 public class SingletonDoubleCheckedLockingTest implements Runnable  
 {  
         public void run() {                        
           System.out.println("Singleton instance id :"+Singleton.getInstance());  
         }  
         public static void main(String[] args)  
         {  
                 System.out.println("Singleton Test!");  
                 SingletonDoubleCheckedLockingTest sei1 = new SingletonDoubleCheckedLockingTest();  
                 Thread thread1 = null;  
                 for(int i=0; i< 2;i++) {  
                         thread1 = new Thread(sei1);  
                         // might create mutliple instances of Singleton class  
                         thread1.start();  
                 }  
         }  
 }  

You can read more about singleton design pattern from the below links:-
http://en.wikipedia.org/wiki/Singleton_pattern