Key notes of Singleton Pattern

Singleton has been one of the most discussed pattern in interviews. These are some key points while writing singleton pattern.

  • Only one object instance is required.
  • Synchronization of getInstance() or only critical section: It is recommended to keep only object creation part in synchronised section to reduce the overhead as it is costly.
  • Lazy or early initialisation: Well if you need object should only be initialized when first time getInstance method is called, this is called lazy initialisation. If object is required to be preloaded then we can use a static block to load the instantiate.
  • DoubleCheck : This is a mechanism to ensure only one object is created while calling getInstance method
    public static SimpleSingleton getInstance(){
    		//double null check
    				_INSTANCE = new SimpleSingleton();
    			System.out.println("Object created");
    		return _INSTANCE;
  • How to prevent cloning: If singleton class is not extending any class then if you do not implement cone method; that is enough to prevent cloning of object of singleton class. If Singleton class is extending any class then optionally you can override its clone() method and you can throw CloneNotSupported exception out of that.
  • Ensure Object is not serializable. As we know that Deserialization can bypass the constructor call and object can be instantiated (Only if class implements Serialization interface). So if we are giving an option to serialize a singleton object then we need to enforce not to read stream object. readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.
            public Object readResolve(){
    		return getInstance();
  • Using Static Inner class in Singleton pattern: Technically it would be treated by a thread as happens before relationship  which you can say as thread safe approach. But the same thing can be done by a static block with pre initialization of singleton object.
    public class Singleton  {
           public static final Singleton _INSTANCE ;
           //1: Simple way of getting object 
           public static Singleton getInstance() {
              if (null == _INSTANCE) {
                    _INSTANCE = new Singleton();
              return _INSTANCE;
           //2: using Static inner class approach
           static Singleton getInstance(){
              return SingletonHolder._INSTANCE;
           static class SingletonHolder{
    	   private static final Singleton _INSTANCE = new Singleton();
           //3: using static block pre initialization approach
           static {
             _INSTANCE = new Singleton();
           public static final Singleton _INSTANCE = new Singleton();
  • Making Singleton object Immutable:

Beauty of Inner Classes

Java allows you to create a class within another class and this is called inner class.

Why to create a nested class? 

  • Logical way of grouping and putting them together. Example say we create class Phone within a class Student to logically group them together.
  • Increases encapsulation; Class Student can access private members of class Phone as being inner class of which, otherwise member variables had to be declared as public to give access to class Student.

These are of several types of inner classes:

1: Static Nested class;  An inner class declared as static can access only static members of parent class .

  public class Student {
	static int roll;
	static String name;

	static class Phone{
		int phone_no;

Static inner class can be access rom out side in following way

InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();

2: Inner Class; A normal non static nested class which is associated with the instance if the holding class.

class OuterClass {
    class InnerClass {

This is how we create instance if inner class:

OuterClass.InnerClass innerObject = InnerClass();

3: Local inner class: Local inner class are those inner classes which are defined within the a specific block. Usually they are defined inside a method , also known as method local inner class. These are highly encapsulated not accessible out side the block , can access members of enclosing class and final local variables.

   public void processData(Data data){
     class DataWorker implements Runnable{
       DataWorker(int data){
       public void run(){

   Thread runner = new Thread(new DataWorker(data));

4: Anonymous inner class: This my favourite and most popular way of using inner class. Here we do not declare a class in advance and then create its object, as we do in traditional way. Rather you can say we construct a class on the fly at the time when its object is required. This is suitable for some composite objects where we need only one object and there we club class declaration and initialisation together.

public void processData(Data data){
    Runnable runable = new Runnable() {
	public void run() {
		// TODO Auto-generated method stub

   Thread runner = new Thread(runable);

Java Collection API -Part 2 (Map)

In continuation of first part of introduction to Java Collection API Part 1, now we would be covering the other part and that is Map api. MAP is designed to store Key-Value pair combination as we know. Some distinct features of MAP are

  • Key can not be repeated
  • Key can be mapped to only one value
  • It depicts mathematical function F(x) -> y , where x represents key and y is the value
  • Basic operations provided by map : get, put , containsKey, containsValue , empty , size
  • Map provides collections views to iterate over the values it holds
    • ketSet      : Set of keys
    • value        : Collection os values, it is not a set as multiple keys can point to same values
    • entrySet  : Map internally contains the set of key-value pair which is represented my inner interface Map.Entry
  • These collections views are good for iteration , modification , removal but CAN NOT BE USED For ADDITION
  • Java API has provided three implementation of MAP interface: HashMap, HashTable, LinkedHashMap
  • MAP also has another sub interface SortedMap which is implemented  by TreeMap


1: HashMap: HashMap is most basic implementation of MAP interface

2: HashTable : Similar to HashMap
-Thread safe and synchronized

3: LinkedHashMap : Values are placed internally as likened list

4: TreeSet : Values are placed in sorted manner. Natural sort of Comparable/Comparator logic is used. It is the similar collection as TreeSet but here Key’s are compared and sorted while putting values in MAP.

Java Collection API -Part 1 (Set , List, Queue)

Java has defined main interface Collection from where all collection APIs are inherited. MAP is another interface which is also another very imported interface which I have covered in my another post Java Collection API Part-2

Collection Interface is subclasses into three another Interfaces:  Set, List and Queue. hierarchy is displayed in below image:


Collection interface provides abstract of following basic operations

  • add(E element)
  • addAll(Collection c)
  • contains(Object e)
  • size()
  • isEmpty()
  • remove(Object o)

In addition to these basic set of operations Specialised collection APIs further add their unique behaviours. Lets see in detail.

1: SET (Interface)
Set Interface is subclass of collection and it is designed to hold Unique values as it is inspired from mathematical set.
-No duplicate values.
-Not indexed

Specialised Implementation of SET
1.1: HashSet class ==>Set, is the basic implantation of Set.
Set is basically good option when you want to count Unique values. Ex Set set = new HashSet(Collection c);

1.2: Linked HashSet class ==> Set is set implantation where internally it maintains linked list where inserted values are also preserved with their order of insertion.

1.3: SortedSet (I) ==> Set it is designed to keep items in sorted values

1.4 TreeSet class==> SortedSet, in sorted set elements are placed in ascending ordered. Elements object class has to define the comparison logic with comparable or comparator.

2: LIST (Interface)
List is an ORDERED collection and can contain DUPLICATE values.
-Duplicate Yes
-Indexed Yes

Some additional methods exposed from List
-add(int index, Object obj)
-set(int index, Object obj)
-addAll(int index, Collection c )  etc

Specialised Implementation of LIST
2.1 ArrayList class ==> List this is a basic implementation of list which dynamically grows its size. You can also specify its initial capacity at the time of creation also.

2.2 Vector class ==>List similar to arraylist but all method are synchronized.

2.3 Linked List class==> List , Dqueue, Cloneable, Serializable
in addition to list it provides all basic operation get, insert, remove from front and back both side. Its Doubly linked List

-addFirst(Object o)
-addLast(Object o)

3: Queue (Interface)
Queue is another direct sub interface of Collection which is designed to hold temporarily objects before they get processed. Queue has some additional methods for basic operation
Queue Interface Structure

Queue Interface Structure
Type of Operation Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

Some major Specialisation of Queue
3.1 DQueue (I) ==> Queue
DQueue is similar to queue but offers all basic operation’s like insert, remove, get from Front and rear both ends.
Front(First)-> [][][][][][] ->Rear(Last)
So operation for add and remove wold be like:
Add: addFisrt, addLast, offerFirst, offerLast
Delete: removeFirst, removeLast, poolFirst, poolLast

3.2 Blocking Queue (I) ==> Queue
Blocking is a Queue that additianaly supports operations that wait for queue to get emplty while adding values or will wait for queue to become non empty while fetching some values.

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable


3.3 PriorityQueue Class ==> Queue
Unbounded queue based on proprity heap, Elements are ordered on natuarl order or based on the Comparator provided in Queue constructor.

3.4 LinkedBlocking Queue Class ==> BlockingQueue, Serialisable ++
Optianally bounded queue based on linked nodes which follows FIFO pattern.


Some of the common good practices I am trying to post here, in case if you some other better practices I would be glad if you can share here by your comments.

  1. Use Iterator or Advance For loop: 

Consider below code

               for(Person p : pList){
			System.out.println("Person Name: " +;

This is not the correct way of modifying the collection, this would give java.util.ConcurrentModificationException since you are trying to modify the collection while iterating over it. Safe way to modify the collection is by using Iterator. Please note even in case of Iterator also it can throw this exception if the collection is modified out side this iteration.

Spring Fundamental Tutorial

Spring First Tutorial

Since intention of this tutorial is to give a brief foundation of Spring framework so its start with covering the following basic modules first and later it would move to advance topics. Tutorial is based on spring 3.0 version.

§Introduction to Spring

§Features added in Spring 3.0+ version

§Spring Framework

§Spring Modules

§Spring IOC & Dependency Injection

§Application Context & Bean Factory

§Spring Bean Configuration

§Auto-wiring in Spring configuration


§Working with Spring Name spaces

§Using Inner Beans 


§Introduction to Spring

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. Spring framework is a layered architecture consisting of seven well-defined modules. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in next Figure .


§Features added in Spring 3.0+ version

  • Spring 3.0 framework supports Java 5. It provides annotation based configuration support. Java 5 features such as generics, annotations, varargs etc can be used in Spring.
  • A new expression language Spring Expression Language SpEL is being introduced. The Spring Expression Language can be used while defining the XML and Annotation based bean definition.
  • Spring 3.0 framework supports REST web services.
  • Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. We can now use the @DateFimeFormat(iso=ISO.DATE) and @NumberFormat(style=Style.CURRENCY) annotations to convert the date and currency formats.
  • Spring 3.0 has started support to JPA 2.0.
  • Apart from these main features there are lots of exiting improvements over the last revisions are also there.


§Spring Framework

§Spring Modules

The core container: The core container provides the essential functionality of the Spring framework. Primary component of the core container are BeanFactory and Application Context, Bean Factory an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code. Application Context is build on top of Bean factory and provides more functionalities, like integration with AOP/messaging resources/events etc.

Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. Spring provides option to specify configuration by XML or Java file based approach.

Spring AOP: AOP is very emerging feature now days which provides more modularity in programming by separating the cross cutting the concerns from main business logic.  The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. . Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

Spring ORM: Spring provides good abstraction layer to integrate with most of the popular ORM tools in market. The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

Spring MVC framework: Spring provides a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and support most of the view technologies like JSP, Velocity, Tiles, iText, and POI.Spring framework functionality can be used in any J2EE server and most of it also is adaptable to non-managed environments. Concentrating more on allowing reusable business and data-access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (Web or EJB), standalone applications, test environments, and so on, without any hassle.


§Spring IOC & Dependency Injection

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked. The three implementation pattern types for IOC are listed below.

  1. Dependencies are assigned through JavaBeans properties (for example, setter methods).
  2. Dependencies are provided as constructor parameters and are not exposed as JavaBeans properties.

Lets see how Spring Uses the Power of simple bean

Most of the traditional frame works forces you to implement their life cycle methods

public class HelloWorldBean implements SessionBean {
    public void ejbActivate() {
    public void ejbPassivate() {

    public void ejbRemove() {
    public void setSessionContext(SessionContext ctx) {

    public String sayHello() {
    return "Hello World";}

    public void ejbCreate() {

The SessionBean interface would let you hook into the EJB’s lifecycle by implementing several lifecycle callback methods, even if you didn’t need to. Spring avoids (as much as possible) littering your application code with its API. Spring almost never forces you to implement a Spring-specific interface or extend a Spring-specific class. Instead, the classes in a Spring-based application often have no indication that they’re being used by Spring. At worst, a class may be annotated with one of Spring’s annotations, but is otherwise a POJO.

  public class HelloWorldBean {
     public String sayHello() {

Isn’t that better? Gone are all of those noisy lifecycle methods. HelloWorldBean doesn’t implement, extend, or even import anything from the Spring API Dependency injection involves giving an object its dependencies as opposed to an object having to acquire those dependencies on its own.

Comparing with the traditional approach of programming vs the spring mechanism. With an interesting example taken from the Book : “Spring in Action 3.0”

Problem: RescueDamselQuest : Mission to rescue a pricess. If we analyse the class written bellow for a moment we can figure out several limitations as described further.

public class DamselRescuingKnight implements Knight {
   private RescueDamselQuest quest;
   public DamselRescuingKnight() {
   //Tightly coupled to RescueDamselQuest
     quest = new RescueDamselQuest();

   public void embarkOnQuest() throws QuestException {

Observed Drawbacks:

  • DamseRescueKnight is tightly coupled to RescueDamselQuest
  • Restricting the ability of Knights for embark on a Quest
  • Terrible writing for test case for DamseRescueKnight , you’d like to be able to assert that the quest’s embark() method is called when the knight’s embarkOnQuest() is called,but is difficult to write such test case.

Better approach to reduce the coupling between the DamselRescuingKnight and RescueDamselQuest, isn’t it.

public class BraveKnight implements Knight {
   private Quest quest;
   public BraveKnight(Quest quest) { = quest;

   public void embarkOnQuest() throws QuestException {

Observed advantages:

  • BraveKnight does not create own Quest
  • Rather he is given a quest at the construction time
  • What more he is give a typed Quest that can receive any kind of Quest, The point here is that BraveKnight isn’t coupled to any specific implementation of Quest

That’s the key benefit of DI—loose coupling. Writing the use case for the above problems also gets more meaning full approach.

   public void knightShouldEmbarkOnQuest() throws QuestException {
      Quest mockQuest = mock(Quest.class);
      BraveKnight knight = new BraveKnight(mockQuest);
      verify(mockQuest, times(1)).embark();

Here you’re using a mock object framework known as Mockito to create a mock implementation of the Quest interface. You really not need to wait to hit the real Quest while Unit test


§Application Context & Bean Factory

Two of the most fundamental and important packages in Spring are the org.springframework.beans and org.springframework.context packages. The BeanFactory provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility

The ApplicationContext builds on top of the BeanFactory (it’s a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling , event handling, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements. Best option is to use the ApplicationContext, since it offers all the features of the BeanFactory and adds on to it in terms of features

Code snippet of getting handler to ApplicationContext/BeanFactory. By providing the reference of the bean configuration file we can get hander of Bean Factory of Application context.

ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");


ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/manjul/../src/Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");


ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/manjul/../src/Beans.xml");
BeanFactory factory = (BeanFactory) context
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

I would suggest to use Application Context over the BeanFactory as it provides you all what BeanFactory does plus some other features. The most commonly used ApplicationContext implementations are:

  • FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
  • ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
  • WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.


§Spring Bean Configuration

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on.A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed.Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean.When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.

The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

  • How to create a bean
  • Bean’s lifecycle details
  • Bean’s dependencies

All the above configuration metadata translates into a set of the following properties that make up each bean definition. Following attributes used with bean tags and their usage is given in below table.

Configuring Spring. Spring provides several ways of defining the Bean configurations as listed below. But I preferably choose XML based configuration, as it provides centralized view of the artifacts to analyze the whole configuration very easily. But its totally up to you that which mechanism you like to implement in your application.

Spring Configuration MetaData

  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration

In a large project structure, the Spring’s bean configuration files are located at different folders for easy maintainability and modular. For example:

  1. Spring-Common.xml in common folder,
  2. Spring-Connection.xml in connection folder,
  3. Spring-ModuleA.xml in ModuleA folder…and etc.

Sample view of Bean configuration File

<beans xmlns="”
<!-- A simple bean definition -->
<bean id="..."singleton">
<!-- collaborators and configuration for this bean go here -->
<!-- A bean definition with lazy init set on -->
<bean id="..." lazy-init="true">
<!-- collaborators and configuration for this bean go here -->
<!-- A bean definition with initialization method -->
<bean id="..." init-method="...">
<!-- collaborators and configuration for this bean go here -->
<!-- A bean definition with destruction method -->
<bean id="..." destroy-method="...">
<!-- collaborators and configuration for this bean go here -->
<!-- more bean definitions go here -->


Scopes of the Beans


§Auto-wiring in Spring configuration

You have seen how to declare beans using the <bean> element and inject <bean> with using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships

between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application. Using following ways/mode.

  • No
  • byName
  • byType
  • Constructor
  • Autodetect

Now we know how to set manual wiring !

<bean id=”customer”>
<property name=”person” ref=”person” />

<bean id=”person” />

Autowiring by property name.

Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” autowire=”byName” />
<bean id=”person” />

Autowiring by property datatype.

Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.

Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” autowire=”byType” />
<bean id=”person” />

Auto-wire Constructore.

Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

Spring auto wired it via constructor method – “public Customer(Person person)“.

<bean id=”customer” autowire=”constructor” />
<bean id=”person”.manjul.spring.samples.Person” />

Auto-wire Autodetect

Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

<bean id=”customer” autowire=”autodetect” />
<bean id=”person” />

Limitations of Autowiring 

Limitations with autowiring:Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing to developers to use it to wire

only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and

disadvantages of autowiring before using them.Limitations Description

Overriding possibility, We can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

Primitive data types,  We cannot autowire so-called simple properties such as primitives, Strings, and Classes.

Confusing nature Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.



Using annotations for the defining Spring configuration file and beans configurations
@Configuration & @Bean Annotations

public class HelloWorldConfig {

public HelloWorld helloWorld(){
return new HelloWorld();

This Is equivalent to
<bean id=”helloWorld” />

While retrieving the bean reference:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class); ctx.refresh();
MyService myService = ctx.getBean(MyService.class);

Autowired Annotation
We have seen how can we define autowiring in configuration file.

We can also specify auto wiring using @Autowired Annotation
Through setter method
public void setPerson(Person person) {
this.person = person;

Through construtor
public Customer(Person person) {
this.person = person;

Through field
private Person person;

By default, the @Autowired will perform the dependency checking to make sure the property has been wired
properly. When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable
this checking feature by setting the “required” attribute of @Autowired to false. @Autowired(required=false)

The @Qualifier annotation us used to control which bean should be autowire on a field. For example, bean configuration file with two similar person beans.

public class Customer
private Person person;
private int type;
private String action;
//getter and setter methods


§Spring NameSpaces

Namespace configuration has been available since version 2.0 of the Spring framework.

It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. You can find more information in the Spring Reference Documentation. A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application.

Name spaces are the preset of liberaries created for a significant purpose i.g. utilities, security, aop etc. Some of the popular libraries are listed below:

Spring core

aop – AopNamespaceHandler
c – SimpleConstructorNamespaceHandler
cache – CacheNamespaceHandler
context – ContextNamespaceHandler
jdbc – JdbcNamespaceHandler
jee – JeeNamespaceHandler
jms – JmsNamespaceHandler
lang – LangNamespaceHandler
mvc – MvcNamespaceHandler
oxm – OxmNamespaceHandler
p – SimplePropertyNamespaceHandler
task – TaskNamespaceHandler
tx – TxNamespaceHandler
util – UtilNamespaceHandler
Spring Security
security – SecurityNamespaceHandler
oauth – OAuthSecurityNamespaceHandler
P-Name space

The p-namespace enables you to use the bean element’s attributes, instead of nested <property/> elements, to describe your property values and/or collaborating beans.

Namespace specification need to be added in configuration file as shown below
Traditional way

<bean name=”john-classic”>
<property name=”name” value=”John Doe”/>
<property name=”spouse” ref=”jane”/>

Using name spaces
<bean name=”john-modern”
p:name=”John Doe”
<bean name=”jane”>
<property name=”name” value=”Jane Doe”/>

Util-Name space

Make sure that we need to have correct XSD loaded”

Ex1 : Generic way for configuring property is
<bean id=”…”>
<property name=”isolation”>
<bean id=”java.sql.Connection.TRANSACTION_SERIALIZABLE”

Using namespaces
<bean id=”…”>
<property name=”isolation”>
<util:constant static-field=”java.sql.Connection.TRANSACTION_SERIALIZABLE”/>

Normal Spring FactoryBean implementation, the PropertiesFactoryBean, to instantiate a java.util.Propertie

Ex2 : Without using name spaces

<bean id=”jdbcConfiguration”>
<property name=”location” value=”classpath:com/foo/”/>

Using name spaces

<util:properties id=”jdbcConfiguration” location=”classpath:com/foo/”/>

One of the collection utility for populating values in list.
<bean id=”emails”>
<property name=”sourceList”>

Ex3: Using Namespace:

<util:list id=”emails”>

*Similarly utilities are also available to work with other collections like Map/Set/Properties

§Using Inner Beans

A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.
An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean.

<bean id=”outer”>
<!– instead of using a reference to a target bean, simply define the target bean inline –>
<property name=”target”>
<bean> <!– this is the inner bean –>
<property name=”name” value=”Fiona Apple”/>
<property name=”age” value=”25″/>

Immutable Objects in Java

Immutable Objects are those objects whose state can not be changed once they are created, example String class is immutable class. Immutable objects can not be modified so they are also thread safe in con current execution.

Features of immutable classes:

  • simple to construct
  • automatically thread safe
  • good candidate for Map keys and Set as their inter sate would not change while processing
  • dont need implementation of clone as they always represent same state

Keys to write immutable class:

  • make sure class can not be overridden
  • make all member variable private & final
  • do not give their setter methods
  •  object reference should not be leaked during construction phase

Example of simple immutable class :

        public final class StudentEnroll{
	    private final String name;
	    private final String regNo;

	    public StudentEnroll(String name, String regNo) { = name;
	        this.regNo = regNo;

	    public String getName(){
	        return name;

	    public String getRegNo(){
	        return regNo;

Rehashing in Java HashMap and Race condition

Hashing – ReHashing and Race condition
Basically while creating a hash map collection assign it a default size (of 10). Later stage when elements are added in the map and after certain stage when you come close to your initial defined capacity there is requirement of ReHashing to retain the performance.

There is LoadFactor defined for the collection (said to be good as .75) and this specifies the good index for time and space.
LARGER load factor => lower space consumption but higher lookups
SMALLER Load factor => Larger space consumption compare to the required no of elements.
Java specification suggests that Good loadfactor value is .75

Hence Suppose you have maximum requirement to store 10 elements in hash then considering the Good Loadfactor .75 = Rehashing would occur after adding 7 elements in the collection. In case if your requirement in this case would not accede to 7 then Rehashing would never occur.

If there are really large no of elements going to be stored in the hashmap then it is always good to create HashMap with sufficient capacity; this is more efficient than letting it to perform automatic rehashing.

RACE condition : While doing the rehasing internal elements which are stored in a linked list for given bucket. They get reverse in the order. Suppose there are two threads encounter the race condition in same time then there are chances of second therad can go in infinite loop while traversal since the order has been changed.

Reference :

Hibernate First Tutorial

Hibernate First Tutorial


2.Hibernate Architecture

3.Main Components of Hibernate

4.Hibernate Configuration

5.Hibernate Mapping File

6.Mapping Association

7.Basic API’s

8.Hibernate Data source properties

9.Complete Example

1: Hibernate Introduction:

While today’s applications are designed using Object Oriented Approach. As the business data is stored in the databases and applications create/fetches/update and remove these data for the business purposes. . Since both data storage and data handling are wast domain, over the period of time they are many vendors have provided mechanism for data data storage like oracle, db2 etc.. and similarly many application development technologies have enhanced theirs capabilities like J2EE,.Net etc.

The basic concept in Object Oriented approach is we consider the solution by identifying different Objects involved in the applications. Where as in case of Data bases there have evolved concept of RDBMS where data is stored in the Relational databases in tables and records. And application developer has to play the role of bridging this gap of data stored in tables and creating objects to be used in the object oriented programming. Developers has to write this data plumbing code as well as data processing code.

Hibernate came up with the solution of bridging this gap and providing all the necessary arrangements through which developer can just configure the required database and tables and later Hibernate will take care of data management work and developer just need to concentrate on data processing i.e. their application programming. Hibernates main advantage is the mapping of Objects data model with the corresponding table, developer do not need to bother about transforming data bases data in to objects. Object creation updation and persistence work will be done by hibernate.

2: Hibernate Architecture

Hibernate architecture is explained in the given figure below. Hibernates persistence layer lies between the data base layer and the application layer.


Hibernate Architecture

Hibernate Architecture

Detailed Architecture

Second figure explains the details architecture with all the components. Session Factory is singleton object for every databases. For every connection there will be a session created by this session factory, which can internally create mutiple transaction bases on the requirement.

Figure 2:

Hibernate Detailed Architecture

Hibernate Detailed Architecture




3: Main Components of Hibernate

Basic building blocks of the hibernate application are listed below:


3.1 SessionFactory org.hibernate.SessionFactory

This is a thread safe singleton immutable object of the database mapping. There is only one connection factory for each database. Its a factory for the hibernate session and it also maintains the second level cache between the application and database at the process level.

Usage example:<to be added>


3.2 Session org.hibernate.Session

This is single threaded an short lived object represents the conversation between the application and the database or persistence store. This is the wrapper over sql connection and works as the factory for the org.hibernate.Transaction. It mentains the first level cache of the application’s persistent object and collections. This cache is used while looking for the object using object id or while navigating the object graph.

Usage example:<to be added>



3.3 ConnectionProvider org.hibernate.connection.ConnectionProvider

This is optional and not directly exposed to the application developer, it represents the pool of connections. If require developer can implement this.


3.4 TransactionFactory org.hibernate.TransactionFactory

This is connection factory for the org.hibernate.Transaction, this is also not exposed to the developer but if require developer can implement this.



3.5 Transaction org.hibernate.Transaction

This is a single threaded short lived object use by the application to specify the atomicity of the work. It abstract the application from underlying jdbc/JTA implementation. Hibernate Session can maintaine more than one transaction also at a time.



3.6 Persistent Object

These are short lived business object represent the persistence state. They are associated with exactly one hibernate session. Once the session is closed they are free to used by the any layer of the application.



3.7 Transient and Detached Object

These are those instance of the persistence java classes whose objects are not yet associated or loaded with the session. They may have been instantiated by the application but not yet been associated with the hibernate session.



4: Hibernate Configuration File


This is the file where we specify the database level configuration. This file is read while application loads and then hibernate creates the connection pool with the specified database as per the specification. It also consist of entire set of mapping of Java Objects and Database tables.

Org.hibernate.cfg.Configuration object represent the entire set of mapping.

Configuarion and Sessionfactory objects:

SessionFactory factory = new Configuration.configure().buildSessionFactory();

Hibernate allows one Session factory for every database. Though it allows multiple session factory for more than one databases.


This is a simple example of the hibernate configuration file.


<?xml version=’1.0′ encoding=’utf-8′?>

<!DOCTYPE hibernate-configuration PUBLIC”-//Hibernate/Hibernate Configuration DTD//EN””&gt;



<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver


<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/mysql


<property name=”hibernate.connection.username”>root</property>

<property name=”hibernate.connection.password”>root</property>

<property name=”hibernate.connection.pool_size”>10</property>

<property name=”show_sql”>true</property>

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=””>update</property>

<!– Mapping files –>

<mapping resource=”contact.hbm.xml”/>




5: Hibernate Mapping File


We specify individual mapping for each database table. Mapping is declared between class with a table and respective column with the attributes of the class.


Mapping can be defined in following ways:

-Using Java 5 Annotations

-Using Hibernate legacy XML file.


5.1 Mapping using Java Annotation

Simple example of hibernate configuration using Annotation, here we can see we are explicitly specifying the mapping in the bean file itself using java 5 annotation.


import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;


@Table(name = “contact”)

public class Contact implements Serializable {

public Contact() {



@Column(name = “id”)

Integer id;

@Column(name = “firstName”)

String firstName;

public Integer getId() {

return id;


public void setId(Integer id) { = id;


public String getName() {

return firstName;


public void setName(String name) {

this.firstName = name;




5.2 Using Hibernate legacy XML file.


The traditional way of declaring the mapping is the hibernate configuration file and we can see in this example how we declare the same mapping by XML file.

This is the most simple and popular way of declaring the mapping, we can also specify the mapping between come other class and table in the same file or we can maintain separate mapping file for each table.



<?xml version=”1.0″?>

<!DOCTYPE hibernate-mapping PUBLIC

“-//Hibernate/Hibernate Mapping DTD 3.0//EN””&gt;


<class name=”roseindia.tutorial.hibernate.Contact” table=”CONTACT”>

<id name=”id” type=”long” column=”ID” >

<generator class=”assigned”/>


<property name=”firstName”>

<column name=”FIRSTNAME” />


<property name=”lastName”>

<column name=”LASTNAME”/>


<property name=”email”>

<column name=”EMAIL”/>





…………………………….article to be completed soon !


Drill Down Pivot Table in Adobe Flex

This has been a very demanding feature among most of the business users to display drill down Pivot Table. In our previous blog we have gone through about how to create a Pivot Table. Drill down Pivot table enable you to click on any cell and it would display the full result set for that summary data.

Previous blog: How to create simple pivot table.
Experience Previous Example
Download the Code

Creating Drill Down Pivot Table:                                                                                                                                                                                                                                                       We can devide the work in four following logical sections. Each one has its own specific purpose.   

1: Adding event listener on Cell Click.

2: Fetching Selected Cell information on Cell Click.

3: Make another service call for this selected information.

4: Display the received drilled data in a grid\popup window or anyother option of your choice.


1: Adding event listener on cell click:

We know that in flex OLAPDataGrid is the UI component to display the Pivot table and OLAPCube is the model object which holds information of Pivot Dimentions.

<mx:OLAPDataGridFONT-SIZE: 10pt; COLOR: #990000; FONT-FAMILY: ‘Courier New'”>myOLAPDG”  defaultCellString=”” visible=”true” itemClick=”olapClick(event)” selectionMode=”multipleCells” allowMultipleSelection=”false” dataProvider=”{dataSet}”      />  

OLAPData grid is very much similar to the dataGrid component. Default grid allows you to select a row at a time, so you will have to specify that your selection usnit is Cell by setting property selectionMode=”multipleCell”.

We can add an event listener by setting it’s itemClick property by specifying a event listener function. You can also do this by using AddEventListener api at on page load. Other properties you see in code snippet are the normal we can specify with any normal pivot table always like dataprovider etc.                                   

2: Fecthing cell data on cell click.
We have written a function by name olapClick and calling the same on pivot click, now lets look into this fucntion. Main job of this fucntion is to findout the clicked cell and its correcponding Row and Column field name and it’s value.

function olapClick(event:ListEvent){
pvtSlectedColNo = event.columnIndex -1 ; // row count starts from 0 , but colum starts from 1
pvtSelectedRowNo = event.rowIndex;
pivotRowField = “EMPLOYEE”;
pivotRowFieldDim = “EMPLOYEEDim”;
pivotColField = “DATE”;
pivotColFieldDim = “DATEDim”;

var op:OLAPAxisPosition = myOLAPDG.selectedItem as OLAPAxisPosition;
var pivotData:OLAPResult= myOLAPDG.dataProvider as OLAPResult;
var cell:OLAPCell = pivotData.getCell(pvtSelectedRowNo,pvtSlectedColNo) as OLAPCell;
var axis:IOLAPResultAxis = pivotData.getAxis(1) as IOLAPResultAxis;
var dim:IOLAPDimension = myMXMLCube.findDimension(pivotColFieldDim) as IOLAPDimension;
var att:IOLAPAttribute = dim.findAttribute(pivotColField) as IOLAPAttribute;
var rowList:IList = att.children;
var temp:IOLAPMember = rowList[pvtSlectedColNo];
pivotColSelected = temp.displayName
var colList:Array = myOLAPDG.columns;
dim = myMXMLCube.findDimension(pivotRowFieldDim) as IOLAPDimension;
att = dim.findAttribute(pivotRowField) as IOLAPAttribute;
var rowList:IList = att.children;
var temp:IOLAPMember = rowList[pvtSelectedRowNo];
pivotRowSelected = temp.displayName;;

In this function we have tried to fetch the value of selectedRow , selectedColumn, and selected Cell data. Later this value would be used for expandable report or view. We can use this piece of information to make another AJAX call by httpService request and once we receive the resultset of the second call we can populate this drilled down information in any other grid or popup window.

yet to write on last two sections…

Experience Drill Down Pivot Table
Download the Code

Create Pivot Table in Adobe Flex

Pivot Table Basic Inroduction:

Pivot table is a very useful tool for data anlysis in multiple dimention. This is one of the most usefull utility in Excel file to transform the tabular data into more useful and analyticl fashion. We can see below in s simple usecase how we can transform tabular data in to pivot table view.

Suppose we have given this source data, it would be little difficult to analys the day basis cost analysis for the employees.



Better solution is to transfor the given tabulare data into Pivot table for the given dimentions.

Pivot View: 


Creating Pivot in Adobe Flex:

Working with DataGrid comonent.

Adobe flex provides us many wiidgets and components for data presenation and data visualisation like table, grid, progressbas, list, pivot table, charts etc…

Befor going into pivot table, it is desired that developer should be comfortable with datagrid component of flex. 

To read more on adobe flex datagrid follow adobe live docs, it is explained in detail there:

We will cover a small overview of datagrid comonent.

DataGrid definition in MXML part:

<mx:DataGrid id=”myDataGrid” dataProvider=”{pivotDataSet}” >
       <mx:DataGridColumn headerText=”EMPLOYEE” ataField=”EMPLOYEE” />
       <mx:DataGridColumn headerText=”DATE” dataField=”DATE”/>
  <mx:DataGridColumn headerText=”COST” dataField=”COST”/>
  <mx:DataGridColumn headerText=”AMOUNT” dataField=”AMOUNT”/>

Those who has worked datagrid would be familiar that we need to define a data provide for this grid and need to populate data through this data provider.

Filling data in dataprovider, we can have a httpService ajax call to fetch data from the servers and load into this data provider. We are not going in that topic as it is a separate section, so we assume that user has written required code to lad data into data provider.Looking at the abstract view of onDataReceive function, which you call upon receiving data from the httpService request.

private function onDataRcv(event:ResultEvent):void
 //fetch data from the result set data, as per your return value

//data structure
   gridData = dataRcvdFromResulSet;

Having code ready till this level we assume that you datagrid is created and data is also populated.

Creating Pivot Table:

Pivot table compponent has two associated objects.

  1. OLAPDataGrid: This object is used to display pivot table on your page, just like dataGrid component.

<mx:OLAPDataGrid id=”myOLAPDG”  temClick=”olapClick(event)”
selectionMode=”multipleCells” allowMultipleSelection=”false”/>

   2.   OLAPCube: Main object, like a model and holds full pivot defenition, inculuding pivot dimentions and hierarchy.


  <mx:OLAPCube name=”FlatSchemaCube”
        <mx:OLAPDimension name=”EMPLOYEEDim”>
            <mx:OLAPAttribute name=”EMPLOYEE” dataField=”EMPLOYEE”/>
            <mx:OLAPHierarchy name=”EMPLOYEEHier” hasAll=”true”>
                <mx:OLAPLevel attributeName=”EMPLOYEE”/>
        <mx:OLAPDimension name=”PRODUCTDim”>
            <mx:OLAPAttribute name=”PRODUCT” dataField=”PRODUCT”/>
            <mx:OLAPHierarchy name=”PRODUCTHier” hasAll=”true”>
                <mx:OLAPLevel attributeName=”PRODUCT”/>

        <mx:OLAPDimension name=”DATEDim”>
            <mx:OLAPAttribute name=”DATE” dataField=”DATE”/>
            <mx:OLAPHierarchy name=”DATEHier” hasAll=”true”>
                <mx:OLAPLevel attributeName=”DATE”/>
        <mx:OLAPMeasure name=”AMOUNT”


 3:   runPvtQuery:  If you see in the above OLAPCude defenition, a function is specified on creation complete = runPvtQuery. Since we have already specified the dataStructure of the Pivot table and if you notice we have also specified the data source also, then what does this function do?.

This functions job is to run a query on this cube for the specified data set to fetch the desired out put.  You can imagine a group by kind of SQL query which gives you data in grouped format, this is also doing something like that.

private function runPvtQuery():void {
            var cube:IOLAPCube = myMXMLCube;
            var query:IOLAPQuery = getQuery(cube);
            var token:AsyncToken = cube.execute(query);
            token.addResponder(new AsyncResponder(showResult, showFault));

 4:   getQuery(): getQuery function actually performs the query on the given data set on the basis of specified dimensions. We cann see here that we have specifed row domension as EMPLOYEE and column dimension as DATE, so it will rearrand the data for the given dimensions and return the data set which can be feeded to the OLAPDataGrid.

 private function getQuery(cube:IOLAPCube):IOLAPQuery {
     var rwId = “EMPLOYEE”;
     var rwDim = “EMPLOYEEDim”;
     var colId = “DATE”;
     var colDim = “DATEDim”;
     var query:OLAPQuery = new OLAPQuery;
     var rowQueryAxis:IOLAPQueryAxis = query.getAxis    (OLAPQuery.ROW_AXIS);
    var RowSet:OLAPSet = new OLAPSet;
   var colQueryAxis:IOLAPQueryAxis = query.getAxis (OLAPQuery.COLUMN_AXIS);        
   var DATESet:OLAPSet= new OLAPSet;
   return query;      


Experience this Example
Download the Code

Blog Likes