About Me

My photo
"Enoughtheory.com" had its humble beginning in the year 2011 by ( Founder of Enoughtheory.com ) Mr Ravi Kant Soni , an Enterprise Java and Spring Framework Specialist, with a bachelor degree (B.E) in Information Science and Engineering from Reva Institute of Technology at Bangalore. He has been into the software development discipline for many years now. Ravi has worn many hats throughout his tenure, ranging from software development, designing multi-tenant applications, integration of new technology into an existing system, to his current love of writing a Spring Framework book. Currently, he is a lead engineer at HCL Technology. Ravi has focused on Web and Enterprise development using Spring Framework for most of his career and has been extensively involved in application design and implementation. He has developed applications for Core-Bank, HR and Payroll System, and e-Commerce systems using Spring Framework. Ravi Kant Soni is author of book "Learning Spring Application development" http://learningspringapplicationdevelopment.com

Friday, 30 August 2013

Singleton Pattern

Motivation

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.


Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

Singleton Implementation - UML Class Diagram
The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

class Singleton
{
 private static Singleton instance;
 private Singleton()
 {
  ...
 }

 public static synchronized Singleton getInstance()
 {
  if (instance == null)
   instance = new Singleton();

  return instance;
 }
 ...
 public void doSomething()
 {
  ... 
 }
}

You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.
The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:


Singleton.getInstance().doSomething();



Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 - Accesing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 - Factories implemented as Singletons

Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Specific problems and implementation



Thread-safe implementation for multi-threading use.

A robust singleton implementation should work in any conditions. This is why we need to ensure it works when multiple threads uses it. As seen in the previous examples singletons can be used specifically in multi-threaded application to make sure the reads/writes are synchronized.

Lazy instantiation using double locking mechanism.

The standard implementation shown in the above code is a thread safe implementation, but it's not the best thread-safe implementation beacuse synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for syncronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any syncronized block. This optimization consist in checking in an unsynchronized block if the object is null and if not to check again and create it in an syncronized block. This is called double locking mechanism.
In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.

//Lazy instantiation using double locking mechanism.
class Singleton
{
 private static Singleton instance;

 private Singleton()
 {
 System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {
  if (instance == null)
  {
   synchronized(Singleton.class)
   {
    if (instance == null)
    {
     System.out.println("getInstance(): First time getInstance was invoked!");
     instance = new Singleton();
    }
   }            
  }

  return instance;
 }

 public void doSomething()
 {
  System.out.println("doSomething(): Singleton does something!");
 }
}

A detialed discussion(double locking mechanism) can be found on http://www-128.ibm.com/developerworks/java/library/j-dcl.html?loc=j

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don't need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.
Singleton - A simple example (java)

//Early instantiation using implementation with static field.
class Singleton
{
 private static Singleton instance = new Singleton();

 private Singleton()
 {
  System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {    
  return instance;
 }

 public void doSomething()
 {
  System.out.println("doSomething(): Singleton does something!");
 }
}


Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This techique has 2 drawbacks that makes singleton inheritance impractical:
  • First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
  • Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().


Multiple singleton instances if classes loaded by different classloaders access a singleton.

If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.


Serialization

If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.

 public class Singleton implements Serializable {
  ...

  // This method is called immediately after an object of this class is deserialized.
  // This method returns the singleton instance.
  protected Object readResolve() {
   return getInstance();
  }
 }


Abstract Factory and Factory Methods implemented as singletons.

There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.

Hot Spot:



  • Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
  • Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
  • Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.


Friday, 16 August 2013

Algorithms and Data Structures

Asymptotic Analysis
  • measuring the cost or complexity of an algorithm
  • Analyzing what happens as the number of inputs becomes very large is referred to as asymptotic analysis

Rate of Growth
  • Rate of growth describes how an algorithm’s complexity changes as the input size grows
  • represented using Big-O notation
  • Big-O notation uses a capital O (“order”) and a formula that expresses the complexity of the algorithm
  • The formula may have a variable, n, which represents the size of the input
  • Constant – O(1) : complexity is constant regardless of how large the input size is. The point is that the size of the input does not influence the time the operation takes.
public int GetCount(int[] items)
{
return items.Length;
}
  • Linear – O(n) : complexity grows linearly with the size of the input.
public long GetSum(int[] items)
{
long sum = 0;
foreach (int i in items)
{
sum += i;
}
return sum;
}

  • Logarithmic – O(log n): complexity is logarithmic to its size. The binary search tree Contains method implements an O(log n) algorithm
  • Linearithmic – O(n log n): A linearithmic algorithm, or loglinear, is an algorithm that has a complexity of O(n log n). Merge sort and quick sort.
  • Quadratic – O(n2):

Linked-List
  • The Node: A node is a container that provides the ability to both store data and connect to other nodes.
public class Node
{
public int Value { get; set; }
public Node Next { get; set; }
}

  • Starts with the node first and ends with the node last.
  • The Next property for the last node points to null which is the end-of-list indicator.
private static void PrintList(Node node)
{
while (node != null)
{
Console.WriteLine(node.Value);
node = node.Next;
}
}

Performance: O(1)

Adding an item to a linked list involves three steps
  1. Allocate the new LinkedListNode instance
  2. Find the last node of the existing list
  3. Point the Next property of the last node to the new node

private LinkedListNode<T> _head;
private LinkedListNode<T> _tail;
Keep track of the last node (the “tail” node) in the list and when we add the new node we simply access our stored reference directly. This is an O(1) algorithm and therefore the preferred approach.



Doubly Linked List
  • LinkedListNode class to have a new property named Previous

Array List
  • Direct indexing of array
  • default constructor initializing the array to size 0
  • Performance: O(n)

Stack
  • A stack is a collection that returns objects to the caller in a Last-In-First-Out (LIFO) pattern.
  • last object added to the collection will be the first object returned
  • The Stack class defines Push, Pop, and Peek methods, a Count property, and uses the LinkedList<T> class to store the values contained in the stack.
  • PUSH: performance – O(1)
  • Pop: performance – O(1)
  • Peek: performance – O(1)
  • Count: performance – O(1)

Queue
  • Queues are a First-In-First-Out (FIFO) collection
  • This means that items are removed from the queue in the same order that they were added
  • backed by a LinkedList
  • Enqueue (to add items), Dequeue (to remove items), Peek, and Count
  • Enqueue : O(1)  ; To the end of queue
  • Dequeue : O(1)  ; To the oldest item
  • Peek: O(1)  ;  Returns the next item that would be returned if Dequeue were called
  • Count: O(1); Returns the number of items currently in the queue. Returns 0 if the queue is empty.

Binary Search Tree
  • Binary search trees take the general tree structure
  • A tree is a data structure where each node has 0 or more children
  • A binary search tree uses the same basic structure
    • Each node can have 0, 1, or 2 children
    • Any value less than the node’s value goes to the left child (or a child of the left child).
    • Any value greater than, or equal to, the node’s value goes to the right child (or a child thereof)
BinaryTree<int> tree = new BinaryTree<int>();
tree.Add(8);
tree.Add(4);
tree.Add(2);
tree.Add(3);
tree.Add(10);
tree.Add(6);
tree.Add(7);






  • Node Class
    • BinaryTreeNode represents a single node in the tree.
    • references to the left and right children (null if there are none)
    • node’s value
    • CompareTo method which allows comparing the node values
  • Binary Search Tree
    • Add, Remove, a Contains method
    • Count and Clear methods
    • To initialize the tree; represents the head (root) node of the tree
    • integer that keeps track of how many items are in the tree
    • ADD: O(log n) on average; O(n) in the worst case
    • Remove: O(log n) on average; O(n) in the worst case
    • Contains: O(log n) on average; O(n) in the worst case
    • Count: O(1)
    • Clear: O(1); head=null; count=0
  • Traversal
    • allow processing each value in the tree

Sorting Algorithm
  • Bubble sort & Quick Sort
  • Swap
    • swap values in an array by index
void Swap(T[] items, int left, int right)
{
if (left != right)
{
T temp = items[left];
items[left] = items[right];
items[right] = temp;
}
}

  • Bubble Sort

Behavior
Sorts the input array using the bubble sort algorithm.
Complexity
Best Case
Average Case
Worst Case
Time
O(n)
O(n2)
O(n2)
Space
O(1)
O(1)
O(1)

    • each time moving the largest unsorted value to the right (end) of the array
public void Sort(T[] items)
{
bool swapped;
do
{
swapped = false;
for (int i = 1; i < items.Length; i++)
{
if (items[i - 1].CompareTo(items[i]) > 0)
{
Swap(items, i - 1, i);
swapped = true;
}
}
} while (swapped != false);
}


  • Insertion Sort
    • Insertion sort works by making a single pass through the array
    • inserting the current value into the already sorted (beginning) portion of the array
    • The important concept is that insertion sort works by sorting items as they are encountered
    • Since it processes the array from left to right
    • we know that everything to the left of the current index is sorted
    • When the sorting process begins, the sorting algorithm starts at index 0
    • Now, array indexes 0–1 are known to be sorted, and 2–n are in an unknown state
    • Now, array from index 0 to 2 is now known to be sorted
    •  
  • Merge Sort
    • Divide and Conquer: algorithms operate by breaking down large problems into smaller, more easily solvable problems
    • example, we use a divide and conquer algorithm when searching a phone book
    • Merge sort operates by cutting the array in half over and over again until each piece is only 1 item long
    • A way to split the arrays recursively
    • A way to merge the items together in sort-order
  • Quick sort
    • divide and conquer sorting algorithm
    • works by recursively performing the algorithm
      • Pick a pivot index and partition the array into two arrays ; using a random number in the sample code
      • Put all values less than the pivot value to the left of the pivot point and the values above the pivot value to the right 

Monday, 12 August 2013

Linked List Implementation In Java

Linked list

In computer science, a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a data and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence.


Singly-linked-list.svg

Linked List Implementation In Java 

1. Insert at The end of the list
2. get size of list
3. print content of list
4.add element at the end
5. add element at specified position
6. remove element at index

Output

----------Size of list---------------
4
----------Content of list----------------
[ 1 ][ 2 ][ 3 ][ 4 ]
----------get element of list-----------------
2
----------remove element from list-----------
true
----------Content of list----------------
[ 1 ][ 3 ][ 4 ]
---add new element to specified position----
----------Content of list----------------
[ 1 ][ M ][ 3 ][ 4 ]

CODE 

/**
 * 1. Insert at The end of the list. 2. get size of list 3. print content of
 * list 4.add element at the end 5. add element at specified position 6. remove
 * element at index
 *
 * Note: The link object doesn't contain the another link object Next Link is
 * actually a reference to another link
 *
 * @author RaviKantSoni[12-August-2013]
 *
 */
public class testSingleLinkedList {

    public static void main(String[] args) {
        SingleLinkedList linkedList = new SingleLinkedList();
        linkedList.add("1");
        linkedList.add("2");
        linkedList.add("3");
        linkedList.add("4");

        System.out.println("----------Size of list---------------");
        System.out.println(linkedList.size());
        System.out.println("----------Content of list----------------");
        System.out.println(linkedList.toString());
        System.out.println("----------get element of list-----------------");
        System.out.println(linkedList.get(2));
        System.out.println("----------remove element from list-----------");
        System.out.println(linkedList.remove(2));
        System.out.println("----------Content of list----------------");
        System.out.println(linkedList.toString());
        System.out.println("---add new element to specified position----");
        linkedList.add("M", 2);
        System.out.println("----------Content of list----------------");
        System.out.println(linkedList.toString());

    }
}

class SingleLinkedList {
    // reference to Head Node
    private Node head;
    private int listCount;

    // LinkedList Constructor
    public SingleLinkedList() {
        // this is empty list so the reference to the head node is set to a new
        // node with no data
        head = new Node(null);
        listCount = 0;
    }

    // add new element to the end of the list
    public void add(String data) {
        Node temp = new Node(data);
        Node current = head;
        // starting at the head node, crawl to the end of the list
        while (current.getNext() != null) {
            current = current.getNext();
        }
        // the last node's next reference set to new node
        current.setNext(temp);
        listCount++;
    }

    // to print content of list
    public String toString() {
        Node current = head.getNext();
        String outPut = "";
        while (current != null) {
            outPut = outPut + "[ " + current.getData() + " ]";
            current = current.getNext();
        }
        return outPut;
    }

    // to get size of the list
    public int size() {
        return listCount;
    }

    // returns the element at the specified position in this list
    // here we are returning object from the list
    public Object get(int index) {
        // index should be 1 or more
        if (index <= 0) {
            return null;
        }
        Node element = head.getNext();
        for (int i = 1; i < index; i++) {
            if (element.getNext() == null)
                return null;

            element = element.getNext();
        }
        return element.getData();
    }

    // remove the element at specific position in the list\
    public boolean remove(int index) {
        // if index is out of range, exist
        if (index < 1 || index > size())
            return false;
        Node current = head;
        for (int i = 1; i < index; i++) {
            if (current.getNext() == null)
                return false;
            current = current.getNext();
        }
        current.setNext(current.getNext().getNext());
        listCount--;
        return true;
    }

    // insert specified element at specified position in the list
    public void add(String data, int index) {
        // insert to requested index or to last in this list, which ever come
        // first
        Node current = head;
        Node temp = new Node(data);
        for (int i = 1; i < index && current.getNext() != null; i++) {
            current = current.getNext();
        }
        temp.setNext(current.getNext());
        current.setNext(temp);
        listCount++;
    }

    static class Node {
        private Node next;
        private String data;

        Node(String data) {
            this.data = data;
        }

        public String toString() {
            return this.data;
        }

        public Node(String data, Node node) {
            this.data = data;
            this.next = node;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

    }
}



Saturday, 3 August 2013

Diameter of a Tree is the number of nodes on the longest path between two leaves in the tree

Diameter of a Tree is the number of nodes on the longest path between two leaves in the tree

Consider a particular "node":- we have three cases
1. Longest Possible path includes node->left and not this node
2. Longest Possible path includes node->right and not his node
3. Longest Possible path includes this "node"

Thus, longest possible path should be maximum of these three: (node->left, node->right, 1+height(node->left) + height(node->right))



OutPut

H
D
B
A
H
D
B
diamater7

Java Code

import java.util.ArrayList;
import java.util.List;

public class longestPathInTree {
    // node class
    class node {
        node right;
        String val;
        node left;

        public String getVal() {
            return val;
        }

        public void setVal(String val) {
            this.val = val;
        }

        public node getRight() {
            return right;
        }

        public void setRight(node right) {
            this.right = right;
        }

        public node getLeft() {
            return left;
        }

        public void setLeft(node left) {
            this.left = left;
        }

        public node(String val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        longestPathInTree path = new longestPathInTree();
        path.find();
    }

    public void find() {
        node root = new node("A");
        node b = new node("B");
        node c = new node("C");
        node d = new node("D");
        node e = new node("E");
        node f = new node("F");
        node g = new node("G");
        node h = new node("H");
        node i = new node("I");
        node j = new node("J");
        node k = new node("K");
        node l = new node("L");
        node m = new node("M");
        node n = new node("N");
        root.setLeft(b);
        root.setRight(c);
        b.setLeft(d);
        b.setRight(e);
        c.setLeft(f);
        c.setRight(g);
        d.setLeft(h);
        d.setRight(i);
        e.setLeft(j);
        e.setRight(k);
        f.setRight(l);
        f.setLeft(m);
        g.setLeft(n);

        int diameter = 0;
        List<node> leftPath = findLongestPath(root.getLeft());
        diameter = diameter + leftPath.size();
        for (int z = leftPath.size() - 1; z >= 0; z--) {
            System.out.println(leftPath.get(z).getVal());
        }
        System.out.println(root.getVal());
        List<node> rightPath = findLongestPath(root.getRight());
        diameter += rightPath.size();
        for (int z = rightPath.size() - 1; z >= 0; z--) {
            System.out.println(leftPath.get(z).getVal());
        }
        System.out.println("diamater: " + ++diameter);

    }

    /**
     * if node does not have child node, then it will be child node else move
     * inside
     *
     * @param n
     * @return
     */
    private List<node> findLongestPath(node n) {
        List<node> stacks = new ArrayList<node>();
        node left = n.getLeft();
        node right = n.getRight();
        stacks.add(n);
        if (left == null && right == null) {
            return stacks;
        } else {
            List<node> sl = new ArrayList<longestPathInTree.node>();
            List<node> sr = new ArrayList<longestPathInTree.node>();
            if (left != null) {
                // Find longest path to left of node.
                sl = findLongestPath(left);
            }
            if (right != null) {
                // Find longest path to right of node.
                sr = findLongestPath(right);
            }
            if (sl.size() >= sr.size()) {
                for (node e : sl) {
                    stacks.add(e);
                }
            } else {
                for (node e : sr) {
                    stacks.add(e);
                }
            }
            return stacks;
        }
    }
}

Friday, 2 August 2013

Tower Of Hanoi









 



Towers of Hanoi 

The objective is to move the entire stack to any other rod, obeying these rules: 
  • Only one disk can be moved at a time
  • Each move consists of taking the upper disk from one rod, adding it onto another rod, on top of any disks that you may have already placed on that rod.
  • But no disk can be placed on top of a smaller disk 
The recursive algorithm
  • move n-1 disk from the starting pole to the pole which is neither start nor target (intermediate)
  • move disk n to the target pole and then move n-1 disk from the intermediate pole to the target pole
  • The n-1 disks are moved recursively 
Pseudo code:
  • if ( nDisks == 1 )    return( "Do this move: fromPeg --> toPeg" ); 
  • else 
    • helpPeg = peg index that is not equal to fromPeg and toPeg; 
    • sol1 = hanoi( nDisks-1, fromPeg, helpPeg );
    • myStep = "Do this move: fromPeg --> toPeg"; 
    • sol2 = hanoi( nDisks-1, helpPeg, toPeg );
How to use the solutions sol1 and sol2 to solve hanoi(nDisks, fromPeg, toPeg): 
 1. first making the moves in sol1
 2. then do myStep
 3. finally, do the moves in sol2

OUTPUT

Move 2 from 2 to 1
Move1from 3 to 1
Move 1 from 3 to 1
Move 3 from 2 to 3
Move1from 1 to 2
Move 1 from 1 to 2
Move 2 from 1 to 3
Move1from 2 to 3
Move 1 from 2 to 3

Java Code

/**
 * three poles and n disks which fit on the poles
 * All disks have different size
 * they are stacked on pole 1 in the orders of their size
 * The largest disk is on the bottom, the smallest is on the top.
 * The task is to move all disk from pole 1 to pole 3 under the following restrictions
 * Only one disk can be moved
 * A larger disk can not be placed on a smaller disk
 *
 * recursive algorithm works like the following: move n-1 disk from the starting pole
 * move disk n to the target pole and then move n-1 disk from the intermediate pole to the target pole
 *
 * n-1 disks are moved recursively
 *
 * @author ravi
 *
 */
public class TowerOfHanoi {
    /**
     * Pole are labeled 1, 2,3
     * Each disk is also labeled
     *
     * @param args
     */
    public static void main(String[] args) {
        move(4, 1, 3);
    }
    /**
     * For first (n-1) elemnet, end pole will be intermediate pole
     * And n element will be moved to last pole
     *
     * @param n
     * @param stratPole
     * @param endPole
     */
    static void move(int n, int stratPole, int endPole){
        if(n==0){
            return;
        }
        if(n==1){
            System.out.println("Move" + n + "from "+ stratPole +" to " + endPole);
        }       
        int intermediatePole = 6-endPole - stratPole;//3+2+1=6
        move(n-1, stratPole, intermediatePole);
        System.out.println("Move " + n + " from "+ stratPole +" to " + endPole);
        move(n-1, intermediatePole, endPole);
    }

}