Sunday, 26 August 2012

Spring Autowiring Qualifier Example

Asynchronous Servlet Example                                                           Heap Generation In java

As we know spring beans are singleton by default, but if we need a two or more than two instance then what should we do to achieve this? In context of this solution spring provides a qualifier annotation to create and use two or more than two instances of a bean.

What is Qualifier annotaion
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument.

How to Use it?


<beans xmlns=""
   <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<task:annotation-driven />
 <bean id="emp" class="" />
 <bean id="engineer1" class="" >
  <property name="name" value="agarwalishant1" />
 <bean id="engineer2" class=" Engineer" >
  <property name="name" value="agarwalishant2" />

Employee class 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Employee {
private Engineer  engineer1;
public Engineer getEngineer1() {
return engineer1;

public void setEngineer1( Engineer  engineer1) {
this.engineer1 = engineer1;
private Engineer  engineer2;
public Engineer getEngineer2() {
return engineer2;

public void setEngineer2( Engineer  engineer2) {
this.engineer2 = engineer2;
public String toString() {
return "Employee [Engineer1=" + + ", Engineer2=" + + "]" ;


Engineer Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

class Engineer
private String name ;
public void setName(String name){ ;
public String getName(){
return name ;

Main class


import org.springframework.context.ApplicationContext;

public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(

Employee emp = (Employee) context.getBean("emp");

So in this example you can see the two instances of the Engineer class but named with different qualifier and
 Employee class will use it and display the desired output.

Sunday, 5 August 2012


Asynchronous Servlet Example                                                           Spring Autowiring


Almost Everybody always have a curiosity that how JVM maintains objects into heap and when garbage collector works  to take out objects from heap ?How object allocate and release from the memory?what is the algorithm JVM follow? so here are some of the answers.

As we know the JVM's heap stores all objects created by an executing Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many potential bugs and headaches

Basically, the Java virtual machine is organized into three generations: a young generation or new generation, an old generation or tenured generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM.

New Feature implemented in JVM implementation in J2SE 5

There are lots of more feature implemented into the implementation of java 5 but now I am talking about Ergonomics feature which provides good performance from the JVM with a minimum of command line tuning . From the java 5 JVM is basically known as smart JVM because before java 5 the initial heap size of 4Mbyte and max heap size of 64Mbyte but from java 5 initial heap size of 1/64 of physical memory up to 1 Gbyte and max heap size of 1/4 of physical memory up to 1 Gbyte.
 The goal of ergonomics is to provide good performance from the JVM with a minimum of command line tuning. Ergonomics attempts to match the best selection of Garbage collector and Heap size  for an application. This selection assumes that the class of the machine on which the application is run is a hint as to the characteristics of the application (i.e., large applications run on large machines). In addition to these selections is a simplified way of tuning garbage collection. With the throughput collector the user can specify goals for a maximum pause time and a desired throughput for an application. This is in contrast to specifying the size of the heap that is needed for good performance. This is intended to particularly improve the performance of large applications that use large heaps. 

JVM Parameters for garbage collection in Java

Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right.  I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and old generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation.

Some Key points to improve the performance of application are:

1) Always nullify to objects at the end of their work.
2) Uses of try and catch block should be less.
3) Use interface instead of Utility class for constants even trying to use enums as much as possible.
4)Use String Builder instead of String Buffer class.
5)Use lazy initialization when there are objects or variables that may never be used, or when you need to distribute the load of creating objects
6)For small collections ArrayList and LinkedList are close in performance, though ArrayList is generally the faster of the two.


1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
5) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.

For asynchronous feature of Servlet click on below link:-

Friday, 27 July 2012

Aynshronous servlet specification

Heap Generation In Java                                                                           Spring Autowiring

Use of Asynchronous Servlet Specification

Use of Asynchronous Servlet Specification

The most basic motivation for asynchronicity in web applications is to handle requests that take longer to complete — possibly running a slow database query, making calls to external REST APIs, or performing other I/O-bound operations. Such requests can quickly exhaust the Servlet container thread pool and affect scalability.
In some cases you may not necessarily have to wait for the processing to complete, e.g. sending an email, kicking off a database job, etc. For such fire-and-forget scenarios you can use servlet's @Async support or place an event  and return immediately, possibly including a confirmation id with the response for later use.
For other cases where the result is required before returning, you'll need a way to decouple request processing from the Servlet container thread in order to improve scalability. To enable this Servlet 3 allows a Servlet to indicate it wants to leave the response open after it has returned so that the request may be completed from a separate thread.
To achieve that the web application can call request.startAsync() and use the returned AsyncContext to continue to write to the response (and eventually finalize it) from a separate thread. From a client's perspective nothing has changed. The request still looks like any other request with standard HTTP request-response semantics.

Below is an example for using asynchronous servlet 3.0 where I am using servlet to accept some parameters from a client and create the POJO'S class object corresponding to it then spool or stored it to a location and then my asynchcronous task is used to insert it into the database(using hibernate version 4).

author:Ishant Agarwal
date:16th july 2012
import java.sql.PreparedStatement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.math.RandomUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

@WebServlet(urlPatterns = "/AsyncDispatcherServlet",asyncSupported=true)
public class AsyncDispatcherServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private static final int NUM_ASYNC_TASKS = 100;
 private ExecutorService exececutor;
 private SessionFactory sessionFactory ;
 public void init() throws ServletException {
  exececutor = Executors.newFixedThreadPool(NUM_ASYNC_TASKS) ;

 public void destroy() {
  exececutor.shutdownNow() ;
 public AsyncDispatcherServlet() {
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
  String name = request.getParameter("name") ;
  int age = Integer.parseInt(request.getParameter("age")) ;
  int salary = Integer.parseInt(request.getParameter("salary")) ;
  String designation  = request.getParameter("designation") ;
  boolean isMarried = Boolean.parseBoolean(request.getParameter("ismarried")) ;
  long transactionID = RandomUtils.nextInt();
  final Employee emp  =  new Employee();
  emp.setTransactionId(transactionID) ;
  emp.setAge(age) ;
  emp.setName(name) ;
  emp.setSalary(salary) ;
  emp.setDesignation(designation) ;
  emp.setMarried(isMarried) ;
  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/spool/" + transactionID));
  oos.writeObject(emp) ;
  oos.flush() ;
  oos.close() ;
  final AsyncContext asynchctx = request.startAsync() ;
  asynchctx.setTimeout(100) ;
  FutureTask task =new FutureTask(new Runnable() {
   public synchronized void run() {
    synchronized (asynchctx) {
    Session session = sessionFactory.openSession() ;
    Transaction tx = session.beginTransaction() ;
     tx.commit() ;
     File f= new File("D:/spool/"+emp.getTransactionId()) ;
     System.out.println("isFileDeleted:" +  f.delete()) ;
     session.close() ;
     }catch(Exception ex){
      ex.printStackTrace() ;
  },null) ;
  asynchctx.addListener(new SimpleAsyncListener()) ;
  exececutor.execute(task) ;
  asynchctx.complete() ;
  System.out.println("Task successfully completed");


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
 private static ServiceRegistry serviceRegistry;

 private static final SessionFactory sessionFactory;
 static {
 try {
 Configuration configuration = new Configuration();
 serviceRegistry = new ServiceRegistryBuilder().applySettings(
 sessionFactory = configuration.buildSessionFactory(serviceRegistry);
 } catch (Throwable ex) {
 System.err.println("Failed to create sessionFactory object." + ex);
 throw new ExceptionInInitializerError(ex);
 public static SessionFactory getSessionFactory() {
 return sessionFactory;

package com.lumata.asynch;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

public class Employee implements Serializable{

public String toString() {
 return "Employee [name=" + name + ", age=" + age + ", isMarried="
   + isMarried + ", designation=" + designation + ", salary=" + salary + ", ID=" + id
   + "]";
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + (int) (id ^ (id >>> 32));
  return result;
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (id !=
   return false;
  return true;
String name ;
Long id ;

public Long getId() {
 return id;
public void setId(Long id) { = id;

Long transactionId ;

public Long getTransactionId() {
 return transactionId;
public void setTransactionId(Long transactionId) {
 this.transactionId = transactionId;
public String getName() {
 return name;
public void setName(String name) { = name;
public Integer getAge() {
 return age;
public void setAge(int age) {
 this.age = age;
public boolean isMarried() {
 return isMarried;
public void setMarried(boolean isMarried) {
 this.isMarried = isMarried;
public String getDesignation() {
 return designation;
public void setDesignation(String designation) {
 this.designation = designation;
public Integer getSalary() {
 return salary;
public void setSalary(int salary) {
 this.salary = salary;
int age ;
boolean isMarried ;
String designation ;
int salary ;

import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;

public class SimpleAsyncListener implements AsyncListener{

  super() ;

 public void onStartAsync(AsyncEvent ae) {
  System.out.println("AsyncListener: onStartAsync" + ae.getAsyncContext().getRequest().isAsyncStarted());

 public void onComplete(AsyncEvent ae) {
  System.out.println("task completed");
 public void onTimeout(AsyncEvent ae) {
  System.out.println("AsyncListener: onTimeout for request: " +
 public void onError(AsyncEvent ae) {
  Employee emp = (Employee)ae.getAsyncContext().getRequest().getAttribute("emp") ;
  System.out.println("Eror employees Id" + emp) ;


 From a server perspective however, async processing has enabled the handling of requests in a more scalable fashion. The following is the sequence of events one more time:
1)Client sends a request
2)Servlet container invokes a servlet (also allocating a thread)
3)The servlet calls request.startAsync(), saves the AsyncContext, and returns
4)The container thread is released but the response remains open
5)Another thread uses the saved AsyncContext to complete the response
6)Client receives the response

For heap generation and garbage collection click on below given link