Sunday 18 November 2012

Spring AOP Advice Ordering

Spring AOP Advice Ordering
Spring AOP Advice Ordering

If you are new to spring AOP. You can go through my previous blog:

Now before we create the sample code for Spring AOP advice ordering, lets see what Spring framework website says on advice ordering:

What happens when multiple pieces of advice all want to run at the same join point? 

Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution. The highest precedence advice runs first "on the way in" (so given two pieces of before advice, the one with highest precedence runs first). "On the way out" from a join point, the highest precedence advice runs last (so given two pieces of after advice, the one with the highest precedence will run second).
When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise the order of execution is undefined. You can control the order of execution by specifying precedence. This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation. Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.
When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined (since there is no way to retrieve the declaration order via reflection for javac-compiled classes). Consider collapsing such advice methods into one advice method per join point in each aspect class, or refactor the pieces of advice into separate aspect classes - which can be ordered at the aspect level.

Spring AOP Advice Ordering Example

In the example below we are trying to use all the 5 advices on the same joinpoint. 
We are going to use the same example that we used in our previous blog on Spring AOP.
We are taking a scenario where there is a small party and different advices are getting used to cater different situations:
  1. @Before advice - Will be used for authentication of guests. Only people in guest list can come. 
  2. @Around advice - Will be used for Audit. Guest's entry and exit timings should be noted. 
  3. @AfterThrowing - Will be used for Exception handling. If a guest gets too drunk then call a cab. 
  4. @AfterReturning - Will be used to Check Normal flow. Give good bye gift to guests who didn't get too drunk.
  5. @After - Will be used to handle both normal or Exception conditions. Send a thank you email to all the guest irrespective of whether they were drunk or not.
We want that the advices to be executed in the following order.
@Before advice
@Around advice
@AfterThrowing
@AfterReturning
@After


Folder structure of the project:


Spring AOP Advice Ordering
Spring AOP Advice Ordering

Lets start with creating a PartyService with letsParty() method to show the use of advices.
 package com.blogspot.javasampleprogram.service;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public interface IPartyService {  
      public void letsParty(PartyPeople people) throws Exception;  
 }  
PartyService Implementation class
 package com.blogspot.javasampleprogram.service;  
 import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class PartyServiceImpl implements IPartyService {  
      /**  
       * guests wait for some time in party then leave.  
       * If a guest gets too drunk then they are taken out.  
       */  
      public void letsParty(PartyPeople people) throws Exception {  
                Thread.sleep(200);  
                // if people get drunk then get them out
                if (people.isDrunk()) {  
                     throw new GotTooDrunkException();  
                }  
      }  
 }  

Data transfer object that stores the information of people coming in.
 package com.blogspot.javasampleprogram.service;  
 import java.io.Serializable;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class PartyPeople implements Serializable {  
      public PartyPeople(){};  
      
      public PartyPeople(String name){this.name = name;};  
      
      public PartyPeople(String name, boolean isDrunk) {
        this.name = name; 
        this.drunk = isDrunk;
      };  
      public String name;  
      public boolean drunk;  
      
     /**  
       * @return the drunk  
       */  
      public boolean isDrunk() {  
           return drunk;  
      }  
      /**  
       * @param drunk the drunk to set  
       */  
      public void setDrunk(boolean drunk) {  
           this.drunk = drunk;  
      }  
      /**  
       * @return the name  
       */  
      public String getName() {  
           return name;  
      }  
      /**  
       * @param name the name to set  
       */  
      public void setName(String name) {  
           this.name = name;  
      }  
 }  
Exception thrown when the guest is not in guestlist
 package com.blogspot.javasampleprogram.exception;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class NotOnListException extends Exception {  
      public NotOnListException() {  
           super();  
      }  
      public NotOnListException(String message) {  
           super(message);  
      }  
 }  
Exception thrown when the guest becomes too drunk
 package com.blogspot.javasampleprogram.exception;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class GotTooDrunkException extends Exception {  
      public GotTooDrunkException() {  
           super();  
      }  
      public GotTooDrunkException(String message) {  
           super(message);  
      }  
 }  

Spring AOP advices :

  1. Before Advice
Before advice is given Order (1) as it should be executed before the Around advice.
Note: On the way in to a joinpoint, the advice with lowest Order value gets executed first.

 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.aspectj.lang.annotation.Before;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.exception.NotOnListException;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(value=1)  
 public class BeforePartyAspect {  

      /**  
       * Advice to log entering and exit of guests.  
       * @param proceedingJoinPoint  
       * @return  
       */  
      @Before(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void checkGuestList(JoinPoint joinPoint) throws NotOnListException {  

           // get method arguments   
           Object[] args = joinPoint.getArgs();  

           // getting the method argument using Joinpoint API  
           PartyPeople partyPeople = (PartyPeople)args[0];  

           boolean onGuestList = false;  
           // checking guest list  
           for (int i = 0; i < partyPeoples.length; i++) {  
                if (partyPeople.getName().equals(partyPeoples[i].getName())) {  
                     onGuestList = true;  
                     break;  
                }  
           }  

           if (!onGuestList) {  
                throw new NotOnListException(partyPeople.getName()+" trying to gatecrash.");  
           }  
      }  

      PartyPeople[] partyPeoples = {new PartyPeople("jason statham"),  
                                          new PartyPeople("john travolta"),            
                                          new PartyPeople("arnold"),            
                                          new PartyPeople("christian bale"),            
                                          new PartyPeople("Vin Diesel")  
      };  
 }  


2. Around Advice

Around advice is given Order (2) as it should be executed after the Before advice

 package com.blogspot.javasampleprogram.aspect;  
 
 import java.util.Calendar;  
 import org.aspectj.lang.ProceedingJoinPoint;  
 import org.aspectj.lang.annotation.Around;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  
 
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 @Aspect  
 @Order(value=2)  
 public class AroundPartyAspect {  
 
      /**  
       * Advice to log entering and exit of guests.  
       * @param proceedingJoinPoint  
       * @return  
       * @throws Throwable   
       */  
      @Around(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void audit(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {  
 
           // get method arguments   
           Object[] args = proceedingJoinPoint.getArgs();  
 
           // getting the method argument using Joinpoint API  
           PartyPeople partyPeople = (PartyPeople)args[0];  
 
          //auditing entry and exit  
           System.out.println(partyPeople.getName()+" came in at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  

           try {  
                proceedingJoinPoint.proceed();  
           } finally {  
                // exit time kept in finally block so that even if there is any exception from method  
                // the exit time still gets audited  
                System.out.println(partyPeople.getName()+" left at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  
           }  
      }  
 }  

3. AfterThrowing advice

Afterthrowing advice is given Order (5) as it should be executed first after the exit from the join point.
Note: On the way out from the joinpoint, the advice with highest Order value gets executed first.
 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.AfterThrowing;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(5)  
 public class AfterThrowingPartyAspect {  

      /**  
       * Advice to send thank You Email to all guests, irrespective of whether they were   
       * too drunk or not.  
       * @param joinPoint  
       */  
      @AfterThrowing(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))", throwing="exception")  
      public void callCabForDrunkGuests(JoinPoint joinPoint, Exception exception) {  

           if (exception instanceof GotTooDrunkException) {  
                // get method arguments   
                Object[] args = joinPoint.getArgs();  
                // getting the method argument using Joinpoint API  
                PartyPeople partyPeople = (PartyPeople)args[0];  
                System.out.println(partyPeople.getName()+" got too drunk. Calling cab!!");  
           }   
           // No need to handle NotOnListException as exceptions thrown by @Before advice never come to @AfterThrowing  
      }  
 }  

4. AfterReturning Advice

AfterReturning advice is given Order(4) as it should be executed after AfterThrowing advice and before After advice. 
 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.AfterReturning;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(4)  
 public class AfterReturningPartyAspect {  

      /**  
       * Advice to give party gift to guests who came out without getting too drunk.  
       * @param joinPoint  
       */  
      @AfterReturning(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void givePartyGift(JoinPoint joinPoint) {  

           // get method arguments   
           Object[] args = joinPoint.getArgs();  

           // getting the method argument using Joinpoint API  
           PartyPeople partyPeople = (PartyPeople)args[0];  
           System.out.println(partyPeople.getName()+" got party gift.");  
      }  
 }  

5. After advice

After advice is given Order(3) as it should be executed last on the way out.
 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.After;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(3)  
 public class AfterPartyAspect {  

      /**  
       * Advice to send thank You Email to all guests, irrespective of whether they were   
       * too drunk or not.  
       * @param joinPoint  
       */  
      @After(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void sendThankYouEmail(JoinPoint joinPoint) {  
 
          // get method arguments   
          Object[] args = joinPoint.getArgs();  

          // getting the method argument using Joinpoint API  
          PartyPeople partyPeople = (PartyPeople)args[0];  
          System.out.println("Sent thank you email to "+partyPeople.getName()+". Thank you "+partyPeople.getName()+" for coming to "+joinPoint.getSignature().getName());  
      }  
 }  

Spring configuration file
 <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
  <beans xmlns="http://www.springframework.org/schema/beans"   
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   

    <!-- The @AspectJ support is enabled by including the below tag -->     
    <aop:aspectj-autoproxy/>   

    <bean id="partyService"    
     class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   

   <!-- Aspect -->  
      <bean id="beforePartyAspect" class="com.blogspot.javasampleprogram.aspect.BeforePartyAspect" />  
      <bean id="aroundPartyAspect" class="com.blogspot.javasampleprogram.aspect.AroundPartyAspect" />  
      <bean id="afterThrowingPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterThrowingPartyAspect" />  
      <bean id="afterReturningPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterReturningPartyAspect" />  
      <bean id="afterPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterPartyAspect" />  

  </beans>   

Run the PartyTest to see who gets party gift and who got drunk:
 package com.blogspot.javasampleprogram.test;  

 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 import com.blogspot.javasampleprogram.exception.NotOnListException;  
 import com.blogspot.javasampleprogram.service.IPartyService;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 public class PartyTest {  

      public static void main(String[] args) {  

           ApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });  

           PartyPeople guest1 = new PartyPeople("jason statham", false);  
           PartyPeople guest2 = new PartyPeople("john travolta", true);  
           PartyPeople guest3 = new PartyPeople("adam sandler", true);  

           System.out.println("--------------------------------------");  

           IPartyService partyService = (IPartyService)context1.getBean("partyService");  

           // in guest list and not drunk  
           try {  
                partyService.letsParty(guest1);  
           } catch (NotOnListException e) {System.out.println(e.getMessage());}  
           catch (Exception e) {}  
           System.out.println("--------------------------------------");  

           // in guest list and drunk. Even if exception is thrown still the exit time is audited  
           try {  
                partyService.letsParty(guest2);  
           } catch (NotOnListException e) {System.out.println(e.getMessage());}  
           catch (Exception e) {}  
           System.out.println("--------------------------------------");  

           // not in guest list and drunk.   
           try {  
                partyService.letsParty(guest3);  
           } catch (NotOnListException e) {System.out.println(e.getMessage());}  
           catch (Exception e) {}  
           System.out.println("--------------------------------------");  
      }  
 }  
Output:
 --------------------------------------  
 jason statham came in at 13:38  
 jason statham got party gift.  
 Sent thank you email to jason statham. Thank you jason statham for coming to letsParty  
 jason statham left at 13:38  
 --------------------------------------  
 john travolta came in at 13:38  
 john travolta got too drunk. Calling cab!!  
 Sent thank you email to john travolta. Thank you john travolta for coming to letsParty  
 john travolta left at 13:38  
 --------------------------------------  
 adam sandler trying to gatecrash.  
 --------------------------------------  

Lets analyse  the results:
Jason who was in the guest list and was not drunk was given the party gift (AfterReturning advice) and was sent thank you email (After advice) and his entry and exit time was audited (Around advice).

John was on the guest list but was drunk so he was not given party gift and cab was called for him (AfterThrowing advice) and was sent thank you email (After advice) and his entry and exit time was audited (Around advice).

Adam who was not on the guest list, was not allowed to enter the party at all (Before advice).

Conclusions

  1. On the way in to a joinpoint, the advice with lowest Order value gets executed first.
  2. On the way out from the joinpoint, the advice with highest Order value gets executed first.
  3. When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined.
Jar files used:
  1. aspectjrt-1.5.3.jar
  2. org.springframework.context-3.0.4.RELEASE.jar
  3. org.springframework.beans-3.0.3.RELEASE.jar
  4. org.springframework.core-3.0.3.RELEASE.jar
  5. org.springframework.asm-3.0.3.RELEASE.jar
  6. org.springframework.expression-3.0.3.RELEASE.jar
  7. org.springframework.aop-3.0.3.RELEASE.jar
  8. com.springsource.org.aopalliance-1.0.0.jar
  9. aspectjweaver-1.6.8.jar



Spring AOP Sample code

Spring AOP Advice example

Spring AOP

As a developer we often consider concerns like business logic, performance, logging, security and so forth while implementing any module. If a single concern is implemented in multiple modules, it leads to lower code reuse and code scattering. For example consider a data access module. If one of the client code need authentication to access the database and another client code may need no authentication at all then placing the authentication code inside the database code might make our code unusable. This is where AOP comes into picture.

AOP (aspect oriented programming) is a programming methodology that enable the modularization of  concerns that cut across multiple types and objects.

AOP Terminologies:


  1. Aspect: a modularization of a concern that cuts across multiple classes. 
  2. Join point: a point during the execution of a program, such as the execution of a method.
  3. Advice: action taken by an aspect at a particular join point. Different types of advice include "around," "before", "after" advice etc. 
  4. Pointcut: a predicate that matches join points.  
Spring AOP supports 5 types of advices:

  1. Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  2. After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  3. After throwing advice: Advice to be executed if a method exits by throwing an exception.
  4. After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  5. Around advice: Advice that surrounds a join point such as a method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Spring AOP Example

In this example, we are taking a scenario where there is a small party and how different advices can be used to cater different situations:







  • @Before advice - Will be used for authentication of guests. Only people in guest list can come. 
  • @Around advice - Will be used for Audit. Guest's entry and exit timings should be noted. 
  • @AfterThrowing - Will be used for Exception handling. If a guest gets too drunk then call a cab. 
  • @AfterReturning - Will be used to Check Normal flow. Give good bye gift to guests who didn't get too drunk.
  • @After - Will be used to handle both normal or Exception conditions. Send a thank you email to all the guest irrespective of whether they were drunk or not.


  • Package Structure:
    Spring AOP Sample code


    Lets start with creating a PartyService with letsParty() method to show the use of advices.
     package com.blogspot.javasampleprogram.service;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public interface IPartyService {  
          public void letsParty(PartyPeople people) throws Exception;  
     }  
    
    PartyService Implementation class
     package com.blogspot.javasampleprogram.service;  
     import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class PartyServiceImpl implements IPartyService {  
          /**  
           * guests wait for some time in party then leave.  
           * If a guest gets too drunk then they are taken out.  
           */  
          public void letsParty(PartyPeople people) throws Exception {  
                    Thread.sleep(200);  
                    // if people get drunk then get them out
                    if (people.isDrunk()) {  
                         throw new GotTooDrunkException();  
                    }  
          }  
     }  
    

    Data transfer object that stores the information of people coming in.
     package com.blogspot.javasampleprogram.service;  
     import java.io.Serializable;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class PartyPeople implements Serializable {  
          public PartyPeople(){};  
          
          public PartyPeople(String name){this.name = name;};  
          
          public PartyPeople(String name, boolean isDrunk) {
            this.name = name; 
            this.drunk = isDrunk;
          };  
          public String name;  
          public boolean drunk;  
          
         /**  
           * @return the drunk  
           */  
          public boolean isDrunk() {  
               return drunk;  
          }  
          /**  
           * @param drunk the drunk to set  
           */  
          public void setDrunk(boolean drunk) {  
               this.drunk = drunk;  
          }  
          /**  
           * @return the name  
           */  
          public String getName() {  
               return name;  
          }  
          /**  
           * @param name the name to set  
           */  
          public void setName(String name) {  
               this.name = name;  
          }  
     }  
    
    Exception thrown when the guest is not in guestlist
     package com.blogspot.javasampleprogram.exception;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class NotOnListException extends Exception {  
          public NotOnListException() {  
               super();  
          }  
          public NotOnListException(String message) {  
               super(message);  
          }  
     }  
    
    Exception thrown when the guest becomes too drunk
     package com.blogspot.javasampleprogram.exception;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class GotTooDrunkException extends Exception {  
          public GotTooDrunkException() {  
               super();  
          }  
          public GotTooDrunkException(String message) {  
               super(message);  
          }  
     }  
    

    Spring AOP advices :

    1. Before Advice 

    Before advice will authenticate guests. Only people in guest list can come.
     package com.blogspot.javasampleprogram.aspect;  
    
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.Aspect;  
     import org.aspectj.lang.annotation.Before;  
     import com.blogspot.javasampleprogram.exception.NotOnListException;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class BeforePartyAspect {  
          /**  
           * Advice to log entering and exit of guests.  
           * @param proceedingJoinPoint  
           */  
          @Before(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void checkGuestList(JoinPoint joinPoint) throws NotOnListException {  
               // get method arguments   
               Object[] args = joinPoint.getArgs();  
               
               // getting the method argument using Joinpoint API  
               PartyPeople partyPeople = (PartyPeople)args[0];  
               
               boolean onGuestList = false;  
               // checking guest list  
               for (int i = 0; i < partyPeoples.length; i++) {  
                    if (partyPeople.getName().equals(partyPeoples[i].getName())) {  
                         onGuestList = true;  
                         break;  
                    }  
               }  
               
               if (!onGuestList) {  
                    throw new NotOnListException(partyPeople.getName()+" trying to gatecrash.");  
               }  
          }  
    
          // guest list
          PartyPeople[] partyPeoples = {new PartyPeople("jason statham"),  
                                              new PartyPeople("john travolta"),            
                                              new PartyPeople("arnold"),            
                                              new PartyPeople("christian bale"),            
                                              new PartyPeople("Vin Diesel")  
          };  
     }  
    
    Spring application context file appContext.xml 
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
     <beans xmlns="http://www.springframework.org/schema/beans"  
          xmlns:aop="http://www.springframework.org/schema/aop"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
         
         <!-- The @AspectJ support is enabled by including the below tag -->     
         <aop:aspectj-autoproxy/>  
         
         <bean id="partyService"   
           class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />  
         
         <!-- Aspect -->  
         <bean id="beforePartyAspect" class="com.blogspot.javasampleprogram.aspect.BeforePartyAspect" />  
     </beans>  
    
    Run PartyTest, 'adam sandler' who is not on the list will be caught by the before advice.
     package com.blogspot.javasampleprogram.test;
      
     import org.springframework.context.ApplicationContext;  
     import org.springframework.context.support.ClassPathXmlApplicationContext;  
     import com.blogspot.javasampleprogram.exception.NotOnListException;  
     import com.blogspot.javasampleprogram.service.IPartyService;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
    
     public class PartyTest {  
    
          public static void main(String[] args) {  
               ApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });  
    
               PartyPeople guest1 = new PartyPeople("jason statham", false);  
               PartyPeople guest2 = new PartyPeople("adam sandler", true);  
    
               IPartyService partyService = (IPartyService)context1.getBean("partyService");  
    
               // in guest list  
               try {  
                    partyService.letsParty(guest1);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
    
               System.out.println("--------------------------------------");  
    
               // @before advice throws NotOnListException   
               try {  
                    partyService.letsParty(guest2);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
    
               System.out.println("--------------------------------------");  
          }  
     }  
    
    Output
     --------------------------------------  
     adam sandler trying to gatecrash.  
     --------------------------------------  
    

    2. Around advice

    Audits the entry and exit time of guests.
     package com.blogspot.javasampleprogram.aspect;  
     
     import java.util.Calendar;  
     import org.aspectj.lang.ProceedingJoinPoint;  
     import org.aspectj.lang.annotation.Around;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AroundPartyAspect {  
          /**  
           * Advice to log entering and exit of guests.  
           * @param proceedingJoinPoint  
           * @throws Throwable   
           */  
          @Around(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void audit(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {  
     
               // get method arguments   
               Object[] args = proceedingJoinPoint.getArgs();  
    
               // getting the method argument using Joinpoint API  
               PartyPeople partyPeople = (PartyPeople)args[0];  
               
               //auditing entry and exit  
               System.out.println(partyPeople.getName()+" came in at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  
               
               try {  
                    proceedingJoinPoint.proceed();  
               } finally {  
                    // exit time kept in finally block so that even if there is any exception from method  
                    // the exit time still gets audited  
                    System.out.println(partyPeople.getName()+" left at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  
               }  
          }  
     }  
    
    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
     <beans xmlns="http://www.springframework.org/schema/beans"  
          xmlns:aop="http://www.springframework.org/schema/aop"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
        
         <!-- The @AspectJ support is enabled by including the below tag -->     
         <aop:aspectj-autoproxy/>  
        
         <bean id="partyService"   
           class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />  
         
         <!-- Aspect -->  
         <bean id="aroundPartyAspect" class="com.blogspot.javasampleprogram.aspect.AroundPartyAspect" />  
     </beans>  
    

    Run the PartyTest, the entry and exit time of each guest is audited.
     package com.blogspot.javasampleprogram.test;  
     
     import org.springframework.context.ApplicationContext;  
     import org.springframework.context.support.ClassPathXmlApplicationContext;  
     import com.blogspot.javasampleprogram.exception.NotOnListException;  
     import com.blogspot.javasampleprogram.service.IPartyService;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
    
     public class PartyTest {  
     
         public static void main(String[] args) {  
    
               ApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });  
    
               PartyPeople guest1 = new PartyPeople("jason statham", false);  
               PartyPeople guest2 = new PartyPeople("john travolta", true);  
    
               System.out.println("--------------------------------------");  
               IPartyService partyService = (IPartyService)context1.getBean("partyService");  
    
               // in guest list and not drunk  
               try {  
                    partyService.letsParty(guest1);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
               System.out.println("--------------------------------------");  
    
               // in guest list and drunk. Even if exception is thrown still the exit time is audited  
               try {  
                    partyService.letsParty(guest2);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
               System.out.println("--------------------------------------");  
          }  
     }  
    

     --------------------------------------  
     jason statham came in at 10:25  
     jason statham left at 10:25  
     --------------------------------------  
     john travolta came in at 10:25  
     john travolta left at 10:25  
     --------------------------------------  
    

    3. AfterThrowing advice

    Handle the GotTooDrunkException and calls cab for the drunk guests.
     package com.blogspot.javasampleprogram.aspect;  
     
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.AfterThrowing;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AfterThrowingPartyAspect {  
     
         /**  
           * Advice to send thank You Email to all guests, irrespective of whether they were   
           * too drunk or not.  
           * @param joinPoint  
           */  
          @AfterThrowing(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))", throwing="exception")  
          public void callCabForDrunkGuests(JoinPoint joinPoint, Exception exception) {  
    
               if (exception instanceof GotTooDrunkException) {  
                         // get method arguments   
                         Object[] args = joinPoint.getArgs();  
    
                         // getting the method argument using Joinpoint API  
                         PartyPeople partyPeople = (PartyPeople)args[0];  
                         System.out.println(partyPeople.getName()+" got too drunk. Calling cab!!");  
               }   
               // No need to handle NotOnListException as exceptions thrown by @Before advice never come to @AfterThrowing  
          }  
     }  
    

    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
      <beans xmlns="http://www.springframework.org/schema/beans"   
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
    
        <!-- The @AspectJ support is enabled by including the below tag -->     
        <aop:aspectj-autoproxy/>   
    
        <bean id="partyService"    
         class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   
    
        <!-- Aspect -->   
        <bean id="afterThrowingPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterThrowingPartyAspect" />   
      </beans>   
    

    Run the above test again. Called cabs for guests, who got too drunk.
     --------------------------------------  
     john travolta got too drunk. Calling cab!!  
     --------------------------------------  
    

    4. AfterReturning Advice

    If the guest is not drunk then no exception will be thrown from method and afterreturning advice will give gifts to these guests.
     package com.blogspot.javasampleprogram.aspect;  
     
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.AfterReturning;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AfterReturningPartyAspect {  
          /**  
           * Advice to give party gift to guests who came out without getting too drunk.  
           * @param joinPoint  
           */  
          @AfterReturning(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void givePartyGift(JoinPoint joinPoint) {  
               // get method arguments   
               Object[] args = joinPoint.getArgs();  
              
               // getting the method argument using Joinpoint API  
               PartyPeople partyPeople = (PartyPeople)args[0];  
              
               System.out.println(partyPeople.getName()+" got party gift.");  
          }  
     }  
    

    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
      <beans xmlns="http://www.springframework.org/schema/beans"   
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
    
        <!-- The @AspectJ support is enabled by including the below tag -->     
        <aop:aspectj-autoproxy/>   
    
        <bean id="partyService"    
         class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   
    
        <!-- Aspect -->   
        <bean id="afterReturningPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterReturningPartyAspect" />   
      </beans>   
    

    Run the above test again. Gift given to only those guests which were not drunk or for which the GotTooDrunkException was not thrown.
     --------------------------------------  
     jason statham got party gift.  
     --------------------------------------  
    

    5. After Advice

     package com.blogspot.javasampleprogram.aspect;  
     
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.After;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AfterPartyAspect {  
          /**  
           * Advice to send thank You Email to all guests, irrespective of whether they were   
           * too drunk or not.  
           * @param joinPoint  
           */  
          @After(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void sendThankYouEmail(JoinPoint joinPoint) {  
     
              // get method arguments   
              Object[] args = joinPoint.getArgs();  
    
              // getting the method argument using Joinpoint API  
              PartyPeople partyPeople = (PartyPeople)args[0];  
              
              System.out.println("Sent thank you email to "+partyPeople.getName()+". Thank you "+partyPeople.getName()+" for coming to "+joinPoint.getSignature().getName());  
          }  
     }  
    
    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
      <beans xmlns="http://www.springframework.org/schema/beans"   
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
    
        <!-- The @AspectJ support is enabled by including the below tag -->     
        <aop:aspectj-autoproxy/>   
    
        <bean id="partyService"    
         class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   
    
        <!-- Aspect -->   
        <bean id="afterPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterPartyAspect" />   
      </beans>   
    
    Run the test again. Every guest (drunk or not drunk) was sent a thank you email.
     --------------------------------------  
     Sent thank you email to jason statham. Thank you jason statham for coming to letsParty  
     --------------------------------------  
     Sent thank you email to john travolta. Thank you john travolta for coming to letsParty  
     --------------------------------------  
    

    My next blog will apply all these advices and in proper order using the @Order annotation.


    Jar files used:
    1. aspectjrt-1.5.3.jar
    2. org.springframework.context-3.0.4.RELEASE.jar
    3. org.springframework.beans-3.0.3.RELEASE.jar
    4. org.springframework.core-3.0.3.RELEASE.jar
    5. org.springframework.asm-3.0.3.RELEASE.jar
    6. org.springframework.expression-3.0.3.RELEASE.jar
    7. org.springframework.aop-3.0.3.RELEASE.jar
    8. com.springsource.org.aopalliance-1.0.0.jar
    9. aspectjweaver-1.6.8.jar


    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