Tuesday, November 25, 2014

Java/J2EE Blog: Object Oriented Patterns and Princples

Java/J2EE Blog: Object Oriented Patterns and Princples: Design Patterns are very important for us to understand if we want to build a software which is re-usable,scalable, maintainable etc. Desi...

Object Oriented Patterns and Princples

Design Patterns are very important for us to understand if we want to build a software which is re-usable,scalable, maintainable etc. Design patterns are high-level abstract solution templates. Think of design pattern as blueprint for solutions rather than solutions themselves.The origins of the design patterns that are prevalent in software architecture today were born from the experiences and knowledge of programmers over many years of using object-oriented programming languages.A set of the most common patterns were cataloged in a book entitled Design Patterns: Elements of Reusable Object-Oriented Software, more affectionately known as the Design Patterns Bible. This book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, better known as the Gang of Four (GoF). They collected 23 design patterns and organised them into 3 groups:- Creational(5), Structural(7) and Behavioral(11).


Creational patterns deal with object construction and referencing. They abstract away the responsibility of instantiating instances of objects from the client, thus keeping code loosely coupled and the responsibility of creating complex objects in one place adhering to the Single Responsibility and Separation of Concerns principles. Following are the patterns in the Creational group:
➤ Abstract Factory: Provides an interface to create families of related objects.
➤ Factory: Enables a class to delegate the responsibility of creating a valid object. 
➤ Builder: Enables various versions of an object to be constructed by separating the construction
for the object itself.
➤ Prototype: Allows classes to be copied or cloned from a prototype instance rather than creating
new instances.
➤ Singleton: Enables a class to be instantiated once with a single global point of access to it.


Structural patterns deal with the composition and relationships of objects to fulfill the needs of larger systems. Following are the patterns in the Structural group:
➤ Adapter: Enables classes of incompatible interfaces to be used together. This pattern is covered
in this chapter.
➤ Bridge: Separates an abstraction from its implementation, allowing implementations and abstractions to vary independently of one another.
➤ Composite: Allows a group of objects representing hierarchies to be treated in the same way
as a single instance of an object. 
➤ Decorator: Can dynamically surround a class and extend its behavior. 
➤ Facade: Provides a simple interface and controls access to a series of complicated interfaces
and subsystems. 
➤ Flyweight: Provides a way to share data among many small classes in an efficient manner.
➤ Proxy: Provides a placeholder to a more complex class that is costly to instantiate. 


Behavioral patterns deal with the communication between objects in terms of responsibility and algorithms. The patterns in this group encapsulate complex behavior and abstract it away from the flow of control of a system, thus enabling complex systems to be easily understood and maintained. Following are the patterns in the Behavioral group:
➤ Chain of Responsibility: Allows commands to be chained together dynamically to handle a request. 
➤ Command: Encapsulates a method as an object and separates the execution of a command from its invoker. 
➤ Interpreter: Specifies how to evaluate sentences in a language.
➤ Iterator: Provides a way to navigate a collection in a formalized manner.
➤ Mediator: Defines an object that allows communication between two other objects without them knowing about one another.
➤ Memento: Allows you to restore an object to its previous state.
➤ Observer: Defines the way one or more classes can be alerted to a change in another class.
➤ State: Allows an object to alter its behavior by delegating to a separate and changeable state
object. 
➤ Strategy: Enables an algorithm to be encapsulated within a class and switched at run time to
alter an object’s behavior. 
➤ Template Method: Defines the control of flow of an algorithm but allows sub classes to override
or implement execution steps. 
➤ Visitor: Enables new functionality to be performed on a class without affecting its structure.

To choose when to use which design pattern is the biggest challenge. When it comes to design patterns, there is no substitute for studying. The more we study the more we become equipped about the pattern. Below are the guidelines that might come handy when choosing a design pattern-

➤ We can’t apply patterns without knowing about them. The first important step is to expand our knowledge and study patterns and principles both in the abstract and concrete form. We can implement a pattern in many ways. The more we see different implementations of patterns, the more we will understand the intent of the pattern and how a single pattern can have varying implementations.

➤ Do we need to introduce the complexity of a design pattern? It’s common for developers to try to use a pattern to solve every problem when they are studying patterns. We always need to weigh the upfront time needed to implement a pattern for the benefit that it’s going to give.Remember the KISS principle: Keep It Simple, Stupid.

➤ Generalize the problem; identify  the issues we are facing in a more abstract manner. Look at how the intent of each pattern and principle is written, and see if your problem fits with the problem that a particular pattern or principle is trying to solve. Remember that design patterns are high-level solutions; try to abstract the problem, and don’t focus too hard on the details of specific issue.

➤ Look at patterns of a similar nature and patterns in the same group. Just because we have used a pattern before doesn't mean it will always be the correct pattern choice when solving a problem.

➤ Encapsulate what varies. Look at what is likely to change in our application. If we know that a special offer discount algorithm will change over time, look for a pattern that will help you change it without impacting the rest of your application.

At the core of all design patterns is the design principles. Software design principles represent a set of guidelines and principles that helps us to avoid having a bad design. The design principles are associated to Robert Martin who gathered them in "Agile Software Development: Principles, Patterns, and Practices". According to Robert Martin there are 3 important characteristics of a bad design that should be avoided:-rigidity, fragility, immobility.The S.O.L.I.D. design principles are a collection of best practices for object-oriented design. All of the Gang of Four design patterns adhere to these principles in one form or another. The term S.O.L.I.D. comes from the initial letter of each of the five principles that were collected in the book Agile Principles, Patterns, and Practices in C# by Robert C. Martin.

Single Responsibility Principle (SRP):-The principle of SRP is closely aligned with SoC. It states that every object should only have one reason to change and a single focus of responsibility. By adhering to this principle, you avoid the problem of monolithic class design that is the software equivalent of a Swiss army knife. By having concise objects, you again increase the readability and maintenance of a system.

Open-Closed Principle (OCP):- The OCP states that classes should be open for extension and closed for modification, in that you should be able to add new features and extend a class without changing its internal behavior. The principle strives to avoid breaking the existing class and other classes that depend on it, which would create a ripple effect of bugs and errors throughout your application.

Liskov Substitution Principle (LSP):-The LSP dictates that you should be able to use any derived class in place of a parent class and have it behave in the same manner without modification. This principle is in line with OCP in that it ensures that a derived class does not affect the behavior of a parent class, or, put another way, derived classes must be substitutable for their base classes.

Interface Segregation Principle (ISP):-The ISP is all about splitting the methods of a contract into groups of responsibility and assigning interfaces to these groups to prevent a client from needing to implement one large interface and a host of methods that they do not use. The purpose behind this is so that classes wanting to use the same interfaces only need to implement a specific set of methods as opposed to a monolithic interface of methods.

Dependency Inversion Principle (DIP):-The DIP is all about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces. It promotes the mantra of coding to an interface rather than an implementation, which increases flexibility within a system by ensuring you are not tightly coupled to one implementation.

This was a brief introduction about Design Patterns and Design Principles. Will try to come up in details about each pattern and principle in upcoming blogs.

Thanks for reading.


Monday, November 24, 2014

Java/J2EE Blog: Why Java Does Not Support Multiple Inheritance

Java/J2EE Blog: Why Java Does Not Support Multiple Inheritance: Why java does not support multiple inheritance? This question is asked very frequently from entry lever to middle level developers in the ...

Why Java Does Not Support Multiple Inheritance

Why java does not support multiple inheritance? This question is asked very frequently from entry lever to middle level developers in the interview. You need to know the reason why java does not support multiple inheritance in order to answer this question in a satisfactory way. Java came in existence after C and C++ and from the experience of C/C++ it was quite evident that multiple inheritance creates more problem than solving them. At the root of this question is is the problem which is caused by multiple inheritance which is know as Diamond problem.

So, lets try to understand what Diamond problem is. Suppose there is a Class A which is the super class for class B and class C. Now there is another class called D which inherits both B and C. This inheritance hierarchy creates diamond like structure.


Now suppose there are two methods with the same name in Class B and Class C and as D inherits from both B and C it will have two versions of that method available to it. So when we create the object of D and try to call such method there will be an ambiguity to which version of the method to call (B's method or C's method). To overcome this situation C/C++ users virtual keyword. Java designers being aware of this problem decided not to support multiple inheritance and came up with the idea of multiple interface inheritance.

If you can tell the interviewer about this Diamond problem you will be able to impress them. However beware of  follow up questions related to interface. One such potential question could be suppose I have two interfaces - InterfaceA and InterfaceB both having a varible called DUPLICATE_VALUE. Now further suppose that a class ClassXYZ implements both the interfaces and we created the instance of ClassXYZ and try to access this DUPLICATE_VALUE through the its instance:-

package com.sanjiv.miscellaneous;

public class TestInheritacne implements InterfaceB, InterfaceA{

/**
* @param args
*/
public static void main(String[] args) {
TestInheritacne t = new TestInheritacne();

t.DUPLICATE_VALUE;

}

}

The above code will fail to compile due to the ambiguity. The solution to it is to call the DUPLICATE_VALUE variable with the interface name as the variables in an interface are all static and final and can be call be called directly-

InterfaceA.DUPLICATE_VALUE

or

InterfaceB.DUPLICATE_VALUE 

Java/J2EE Blog: Hello Spring MVC

Java/J2EE Blog: Hello Spring MVC: In this blog I will create a very simple Spring MVC demo to get started with Spring MVC. A prior exposure to any MVC framework will be hand...

Sunday, November 23, 2014

Hello Spring MVC

In this blog I will create a very simple Spring MVC demo to get started with Spring MVC. A prior exposure to any MVC framework will be handy to understand Sprig MVC. I will be using Tomcat 7.0 as web server and Spring3.2 release.

Lets create a dynamic web project in eclipse and name it Spring MVC. This is how the folder structure will look like-










At his moment its simple web project with no spring related  capabilities. First we will create a simple web application with welcome.html as the welcome file to get going and then we will add Spring MVC features to it. Below is the content of my wlecome.html page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>
<h3>Welcome to Spring MVC</h3>
</body>
</html>

Just run the html page and you will get the output like below:-









Now lets start adding Spring MVC  realted stuff to the application. The first thing that we will do is to add spring-webmvc.jar to the classpath as we are going to use the classes/interfaces from spring-webmvc. Right click on the project->properties->java build path and then add the spring-webmvc.jar by browsing to the location where you have downloaded it.Apart from spring-webmvc.jar we also need the follwing jars in the WEB-INF/lib directory or you can also copy them directly in your Tomcat/lib folder but not on both places else you will get linkage error at run time.Below is the list of jars-






Now that we have got all the required jars, lets configure the front controller component. Every MVC framework has a front controller which is responsible to to handle all the incoming request and route it to the controller that will be responsible for handling the request. In sturts its the ActionServlet, but in spring its DispatcherServlet. Lets configure the front controller of the Spring MVC in the web.xml file by making the following entry-

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/springmvc-config.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

The contextConfigLocation init  parameter tells spring about the configuration file where we define out applicaiton related controller and view components.The default name for this file is the name of ur DispatcherServlet(springmvc)-servlet.xml file. If we use the default file name then there is no need to define contextConfigLocation parameter. Here i am not using the default. If i had used the default the name of file would have been springmvc-servlet.xml. The url-pattern tells that any request ending with .htm will be routed to the DispatcherServlet to route it further to the controller. The url-pattern can be any url pattern that you wish, its a spring convention to user *.htm. You can choose whatever you like.

Next we need to define our controller component that will handle our request. In our sample application we will direclty invoke /hello.htm from the broswer. So we need one Controller that will handle this request. Lets call this Controller HelloController-

package com.sanjiv.spring.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloController implements Controller {
   
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        return new ModelAndView("hello","message",message);
    }

}

Now that we have created the controller lets configure this controller in springmvc-config.xml file-

  <bean name="/hello.htm" class="com.sanjiv.spring.mvc.controller.HelloController">
      <property name="message">
          <value>Welcome to Spring MVC</value>
      </property> 
  </bean>

The name of the bean is the url that we will hit from the browser.HelloController has one simple message property which i am populating here using setter injection with value "Welcome to Spring MVC". Our HelloController implements Controller interface and overrides its handleRequet() method which returns a ModelAndCView() object. I will not explain all the details of all components here as our target here is to just get started with spring MVC. Based upon this ModelAndView object the DispatcherServelt decides whihc view to call and for this it contacts ViewResolver. So we need to configure view resolver as well which will route the request to the jsp which will render the final output to the user. hello is the logical name of our jsp page which is used by the View Resolver to generate the physical view which will be /jsp/hello.jsp page. lets configure view resolver in springmvc-config.xml file-

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
All our jsp files are inside the jsp folder in webcontent directory.

Now lets create hello.jsp inside the jsp folder that will render the final output with the message string parameter that we are passing from the controller-

<%@page import="java.util.Date"%>
<html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
<h1><%= request.getAttribute("message") %></h1>
<%= new java.util.Date() %>
  </body>
</html>

So we are all set to go now. Lets run the application by hitting the url-http://localhost:8080/SpringMVC/hello.htm. and you can see the below output-


Thats it we have created our first Hello Spring MVC application.

Below is the flow of control:-

1 DispatcherServlet receives a request whose URL pattern is “/hello.htm”.
2 DispatcherServlet consults HandlerMapping to find a controller
whose bean name is “/hello.htm”, finding the HelloController bean
3 DispatcherServlet dispatches the request to HelloController for processing.
4 HelloController returns a ModelAndView object with a logical view name
of hello.
5 DispatcherServlet consults its view resolver (configured as InternalResourceViewResolver)
to find a view whose logical name is hello. Internal-
ResourceViewResolver returns the path to /jsp/hello.jsp.
6 DispatcherServlet forwards the request to the JSP at /jsp/
home.jsp to render the hello page to the user.

This was the very basic demo to get going. In my coming blogs I will explain each and every componnent of spring MVC in details.

Thanks for reading.










Friday, November 21, 2014

Java/J2EE Blog: Understanding HashMap

Java/J2EE Blog: Understanding HashMap: HashMap is one of the most widely used collection class. If we do not understand how Hash Map internally works, it can be very difficult to...

Understanding HashMap

HashMap is one of the most widely used collection class. If we do not understand how Hash Map internally works, it can be very difficult to answer the has map related interview questions. In this blog I will be explaining in details about Hash Map and how it works internally so that it can be easier for us to answer the questions asked in the interview as well as for our better understanding.

But before we move into the details of Hash Map there are couple of things that we need to understand beforehand. These concepts will come handy when explaining the internal working of a Hash Map. The two things that i want to explain here is equals() and ==. equals() method is basically used to compare the logical equality of two objects whereas == is used to compare two object references (address). Suppose I have a class Employee with three attributes - name, age and sex.

package com.sanjiv.collection;

public class Employee{

private String name;
private int age;
private String sex;

public Employee(String name, int age, String sex){
this.name=name;
this.age=age;
this.sex=sex;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}
}

Now suppose i create two objects of Employee class, say emp1 and emp2 with same attribute value.

emp1 = new Employee("Chander",35,"Male");
emp2 = new Employee("Chander",35,"Male");

As emp1 and emp2 creates two objects they are pointing to two different memory location in the  heap and thus the emp1==emp2 returns false. Which is quite understandable. But if I say-

emp1 = new Employee("Chander",35,"Male");
emp2=emp1;

This will return true as emp2 is assigned the reference to emp1 and thus both of them are pointing to the same memory location.

Now lets say -

emp1 = new Employee("Chander",35,"Male");
emp2 = new Employee("Chander",35,"Male");

Logically these two objects are equal, so when i call emp1.equals(emp2) it should return true. But surprisingly it retruns false. The reason for this is that i have not overridden the equals() method and thus it inherits the default behavior of  equals() method from Object class which does a == check, and == will check for the address that they are pointing to and thus returns false. This is not the case when u call the same equals() method on String objects or say any other Wrapper Classes object as they all have overridden the equals() method to do a logical comparison rather than inheriting the default behavior and compare the memory address.

Now lets get back to HashMap. A hash map works on the hashing technique and hashing is basically a value returned by the hashcode() method of hash map class. At the moment think of hash code as a memory location in the heap which is used to store objects. As we all know map is used to store key,value pairs, lets say we create and Employee object and use it as a key inside our map. Here i am mapping employee key to the city(value) where he/she lives. In the below code Employee Chander lives in city Pune.

Employee emp1 = new Employee("Chander",35,"Male");

Map map = new HashMap();
map.put(emp1,"Pune");


Now lets say we want to search the same Employee if it exists in the map or not.

Employee searchEmp =new Employee("Chander",35,"Male");
map.get(searchEmp);

But surprisingly we are not able to find this employee in the hash map although it exists there. Lets try to explain what is happening behind the scene and explain the behavior. Basically we are doing put and get operation on the has map and each time when put or get is called it calls the hashcode() method to determine where in the memory to put/get the object from. So when we first called the put method suppose the hascode() for emp1 returned a memoery address of 1000X and the object was stored at 1000X memory location. Then to search the key we called the get() method but this time the hashcode method for searchEmp returned 2000X memory address. and there was no object found at that memory address and thus it returned the value false. So for two identical objects the hash code should always be identical to fetch them from the map. If we don't override the hascode() method our has map will be inconsistent.

Now lets override the hascode() method and see how it goes. I am intentionally returning the same hashcode for each and every object that will be created for the Employee class so that they all fall in the same bucket or memory address (linked list is used internally which will point to the next object in the list).


public int hashCode(){
return 100;
}

Strangely it still returns false. The reason being i have not overridden the equals() method. So once the get() method is able to identify the bucket it calls the equals() method to compare the object stored  in the map with the object that we have passed it as parameter. And as I have not overridden the equals() method it calls the default implementation given in the Object class which as explained earlier does == check. And a == check will compare the memoery address of searchEmp and the object stored in the map. Both of them certainly have two different memory locations.

Now lets override the equals() method as well.


public boolean equals(Object obj){
if(obj instanceof Employee ){
Employee emp =  (Employee)obj;
if((this.name==emp.name)&&(this.age==emp.age)&&(this.sex==emp.sex))
return true;

}
return false;
}

Now the map returns true. First it identifies the memory location by calling he hashcode() method and then compares both the objects using the equals() method. The equals() check if all the attribute values are equal or not if it is equal it returns true.So, basically fetching the object from hash map is a two step process. First identify the memory location where it can be stored and then compare the stored value in the map with the value we are searching for.

An efficient implementation of  hashCode() will return distinct code for each distinct object and thus only one object will be stored in each bucket which will require less number of comparision and faster search of keys in the has map. In my case all objects fall in the same bucket which will require more comparision and less efficient hash map.

There is contract between hashcode and equals method. If you override equals you must override hashcoe and vice-versa.

Hash Map does not allow duplicate key, so if you insert the same key it will replace the value corresponding to that key. The follwoing code will replace the value corresponding to the emp1 key from Pune to Mumbai.

map.put(emp1,"Pune");
map.put(emp1,"Mumbai");

I have tried to keep it simple and still explain the concept of Hash Map. Hope it helps the readers in understanding the basic concept. There is still a lot to discuss about but for basic understanding i hope this helps.

Let me know your views.

Thanks for reading.









Thursday, November 20, 2014

Java/J2EE Blog: CallBy Value vs CallBy Reference

Java/J2EE Blog: CallBy Value vs CallBy Reference: Java is call by value or call by reference. This question is asked very frequently in java interviews and can get very confusing if you do ...

CallBy Value vs CallBy Reference

Java is call by value or call by reference. This question is asked very frequently in java interviews and can get very confusing if you do not know the concept of java programming language. As a rule of thumb always remember that java is always call be value irrespective of passing a primitive or passing an object. In case of primitive its very clear Lets try to demonstrate this by an example code.


package com.sanjiv.miscellaneous;

public class PassByValueOrReference {

public static void main(String[] args) {

int x = 10;
System.out.println("Before function call: " +x);
add(x);
System.out.println("After function call: " +x);
}

private static void add(int x) {
x = x + 5;

System.out.println("Value inside the function:" +x);

}


The output of the above program is :-

Before function call: 10
Value inside the function:15
After function call: 10

Which is very obvious. In java primitives are stored in stack and each method has its own stack. Here there will be two stack created one for main stack and the other one for add stack. When we call the add method add stack will have its own copy of int x. So whatever changes it makes to its own stack will not be reflected to the variable declared in main stack.

Things get a bit tricky when we pass an object as parameter. Lets try to demonstrate through code example.

package com.sanjiv.miscellaneous;

public class PassByValueReference {

/**
* @param args
*/
public static void main(String[] args) {
Employee acutalEmp;//1
acutalEmp = new Employee("Sanjiv");//2
System.out.println("Name before method call: " +acutalEmp.getName());
modify(acutalEmp);
System.out.println("Name after method call: " +acutalEmp.getName());
}
private static void modify(Employee formalEmp) {//3
formalEmp.setName("Kumar");//4
formalEmp = new Employee("Rajeev");//5
}



}


class Employee{
private String name;
Employee(String name){
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

The output of the above code is:-

Name before method call: Sanjiv
Name after method call: Kumar


Here whatever change we made to the employee object inside the modify() method is reflected in the main method as well. This creates the illusion that java passes object by reference which is not true.

Lets try to explain this behavior for clear understanding. I have put some marker in the code to explain it in detail. As said earlier both the methods-main and modify will have its own call stack. Java stores objects in Heap and not stack. Keep this point always in your mind. At line 1 we are creating a reference variable for Employee object. At this point no object is created. actualEmp reference is local to main method call stack. At line two we are creating a Employee object which naturally gets created on the heap. Suppose this object has a memory address 1000X assigned to it. So our actualEmployee reference is poining to 1000X memory location which holds the object. At line 3 the modify method formalEmp declares its own reference which again is local to modify method stack. But both actualEmp and formalEmp are pointing to the same memory location which is 1000X. So whatever change we are making at line 4 will be reflected in all the references that are pointing to the 1000X memoery location, which in this case is acutalEmp and formalEmp reference. To clarify things i have crated a new object at line 5. Suppose this time a new memory location of 2000X is assigned to the Employee object referenced by formalEmp reference. So after the execution of line 5 formalEmp starts pointing to 2000X memory location whereas the actualEmp reference is still pointing to 1000X. Had this been call by reference both would have pointed to 2000X memory location which is not the case. After the execution of line 5 any change made to the employee object will not be reflected in the actualEmp reference as both of them are now pointing to two different memory locations - 1000X and 2000X respectively.

Hope this explains the fact that java is always call by value and not call by reference.

Please feel free to post your comments and suggestions.




Java/J2EE Blog: Singleton Design Pattern

Java/J2EE Blog: Singleton Design Pattern: Singleton Design Pattern is one of the simplest but the trickiest of all design patterns. It falls under Creational Pattern. During intervi...

Singleton Design Pattern

Singleton Design Pattern is one of the simplest but the trickiest of all design patterns. It falls under Creational Pattern. During interview lots of cross questions can be asked by the interviewer which can be very tricky to answer if you do not know them. In this blog i will cover all of them. I will start with the simplest and move towards the complicated one.

But before we move on lets have a shot introduction of Singleton Pattern. As we all know a Singleton Pattern helps us in situation where we want to have just one instance of class in our application at any given point of time. This is achieved by declaring the constructor of the class as private so that the outside world can not create the instance of our singleton class and provide a factory method like get instance to create the instance of the class.

Lets see this through code demonstration:-

package com.sanjiv.designpatterns.singleton;

public class MySingleton {

private static MySingleton INSTANCE = null;

private MySingleton(){
}


public static MySingleton getInstance(){

if(INSTANCE == null){
INSTANCE = new MySingleton();
}

return INSTANCE;
}

}

The above code works fine if we are working in a single threaded environment but breaks in a multi-threaded environment as two threads can at a time call the getInstance() method and they both find that the INSTANCE variable is null and both thread end up creating instance of a singleton class. So the above code might break in a multi-threaded environment.

The easiest solution to make the singleton thread-safe is use Eager Initialization.

package com.sanjiv.designpatterns.singleton;

public class EagerlyInitializedSignleton {

private static final EagerlyInitializedSignleton instance = new EagerlyInitializedSignleton();

//make the constructor private
private EagerlyInitializedSignleton(){

}



public static EagerlyInitializedSignleton getInstance(){

return instance;

}
 If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios Singleton classes are created for resources such as File System,  Database connections etc and we should avoid the instantiation until unless  client calls the getInstance method. Also this approach doesn’t provide any options for exception handling.

The first approach that we used in the begining to demonstrate Singleton Pattern uses Lazy Initializaion but its not thread safe. So lets try to make that thread safe. One way to do that is to make the getInstance method thread safe by using the synchronized key work as below:-

public static synchronized ThreadSafeSingleton getInstance(){

if(instance == null){
instance = new ThreadSafeSingleton();
}

return instance;
}


The above code works fine in a multithreaded environment but comes with some performance penalty. The only realistic time when the threads need to synchronize is for the first time, once the instance is created there is not need to synchronize. So this isnt the best of the approaches to create a singleton in a multi-threaded environment.

To overcome this situation the double checking mechanism can be used. Lets see this through code demonstration:-

public static ThreadSafeSingleton getInstanceUsingDoubleChecking(){

if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}

}
}

return instance;
}

This seems a better way to create a singleton class in a multi-threaded environment. But this also has some limitation. Like suppose your singleton class uses serializable interface. So when a serilaizable singleton class is de-serialized we will end up having two instances of the same class. To avoid this we can write our own implementation of the readResolve() method and can call the getInstance() method from within.


protected Object readResolve() {
   return getInstance();
}

We can still clone() the class and create more than one instance of it. If the interviewer asks, tell that for a class to be clonable it has to implement clonable interface. Now he says that our class implements clonable interface then how will you ensure that we dont have multiple instance of the singleton. The best way to do that is to throw CloneNotSupported exception from the clone method. This way you can restrict your clients from creating more than one instance by cloning the object.


protected final Object clone() throws CloneNotSupportedException{


throw new CloneNotSupportedException();


}


But still the Singleton Class can have multiple instance by using java reflection API. We can create more than one instance on the fly by using Reflection.Well the solution to all the problems(seriliazble,clonable and reflection) is to use Enum to carate a singleton. Its the easiest and safest way to create a singleton.

public enum SingletonEnum{

INSTANCE


}

It is as simple as that and saves you from a lot of headache.

Bill Pugh came up with his solution of implementing a Singleton. This is also worth to have a look. He came up with the idea of using inner static class to create a singleton.

public class BillPughSingleton {

private BillPughSingleton(){}

private static class SingletonHelper{

private static final BillPughSingleton instance = new BillPughSingleton();
}

public static BillPughSingleton getInstance(){

return SingletonHelper.instance;
}
}


Please leave your comments and suggestions.

Thanks for reading.