Monday, December 5, 2016

yield() vs join() vs sleep()

This is another popular core interview question. Look at the following table.


yield() vs sleep()

  • Both methods are used to stop execution of current thread.
  • But the different is, yield() method release its lock of object while sleep() method doesn't release its lock of object. 

wait() vs sleep()

  • sleep() method allows to thread to go to sleep state for given time. As you know, it doesn't release the lock of object.
  • wait() allows thread to release the lock and goes to blocked state. It can be active only by calling notify() or notifyAll() methods.

notify() vs notifyAll()

  • notify() method activate the first thread which called wait().
  • notifyAll() method activate all threads which called wait(), highest priority thread will run first.



Saturday, July 30, 2016

Deadlock in Java

csunplugged.com


When we talk about threads, Deadlock is another important thing. If you are a beginner, this may be very useful when you face an interview.


What is called Deadlock ?

Deadlock is caused by multiple threads are blocked and waiting for each other to release the lock of the object.

At the time they are waiting each other forever. Look at the following code. Then you may understand it.


ParentClass.java

package com.app;

public class ParentClass {
   final String s1 = "A";
   final String s2 = "B";
}


ThreadOne.java

package com.app;

public class ThreadOne extends ParentClass implements Runnable{

   public void run(){
       synchronized (s1) {
           System.out.println("ThreadOne s1");
           try{
               Thread.sleep(100);
           }catch (Exception e){ }
           synchronized (s2){
               System.out.println("ThreadOne s2");
           }
       }
   }
}


ThreadTwo.java

package com.app;

public class ThreadTwo extends ParentClass implements Runnable {

   public void run(){
       synchronized (s2){
           System.out.println("ThreadTwo s2");
           try{
               Thread.sleep(100);
           }catch (Exception e){ }
           synchronized (s1){
               System.out.println("ThreadTwo s1");
           }
       }
   }
}


Application.java

package com.app;

public class Application {

   public static void main(String[] args){
       Thread t1 = new Thread(new ThreadOne());
       Thread t2 = new Thread(new ThreadTwo());
  
       t1.start();
       t2.start();
   }
}



Sometimes it looks complex, but it is easy to understand. When you run this, you may get one of following results.

ThreadOne s1 
ThreadTwo s2 

or

ThreadOne s2
ThreadTwo s1

Deadlock is critical  

It is very difficult to test for deadlocks. You may know that, testing a multithreaded application is very difficult task. This the main disadvantage of using threads. Then you can understand about the situation with Threads + Deadlocks. 

Because deadlocks depend on system, environment, underlying hardware etc.

What is caused for deadlocks ?

Mainly deadlocks are caused by inconsistent lock ordering of objects. If you have any idea to detect deadlocks it may help you to prevent deadlocks.

How to prevent a deadlock ?

  • Use multi-threads, only if it is must
As you know, if you use multi threads; it makes your code more complex. So you can choose multi threading only if you want in your application.

  • Order locks
If you can arrange your locks according to an order, then it will avoid conflicts with each locks. So what you can do is; assign a numeric values to each lock and you should order them according to the priority of those locks. 

But you should have a good understand about locks and when they are needed for each other.

  • Set lock timeout 
You can set timeout to remove conflicts between locks. You can build the mechanism to rebuild to application for random timing if it detects a deadlock. Then it will run continuously without giving any chance to deadlocks. 

  • Keep lock private (Encapsulate locks)
Make locks private, then complete control is in your hand. Don't share data between threads if it is not necessary.

  • Look for other alternative ways
You can use volatile fields, then it doesn't require lock and multiple threads can access the latest value of the field.

  • Focus about deadlocks in application design time
This may be help to avoid deadlocks because deadlocks are unpredictable at sometimes. If you study more about the system in design time it may help you to avoid deadlocks.


  • Always try to shrink synchronization blocks or methods

This may help to make your design easier to it will make easy to understand about potential deadlocks. Because it is easy to check in small blocks rather than huge blocks.






Friday, July 29, 2016

Volatile keyword


Cached variables

Just think about a multithreaded application. In this kind of applications they are using cached variables for working. Normally threads may copy variables from CPU to cache memory to access them fast. These variables are called cached variables. This operation may increase application performances. If your system have multi cores, then variables will be cached to different CPU's cache memories. 

At the time, if one thread changes the value of a variable which is in one cache memory, it can't be guaranteed that it will get updated in other threads. because different threads are using different cached memories. That is why we need volatile variables.


What is Volatile ?

  • Volatile is a non access modifier
  • You can use it only with variables(fields), you CANNOT use it with classes and methods.

Volatile variables

  • If you define a variable with volatile modifier; it says to Java compiler, don't cache the value of this variable and it should read only from the main memory. So Java compiler doesn't copy this variable to cache memories and always uses original copy of the variable. 
Just think for moment, in your multi threaded application, you just want to update any value and that updated value need to be used in another thread. In multi threaded application, it will run different threads in different cores in multi core processors. At the time each thread cache its variables to the processor cache (Look at the top of this post)

If I change one value in one thread which is running in one CPU, may not be updated in another thread. This thread may be using old value. This will make troubles to the application. 

The best option to avoid this, make that variable volatile

When to use volatile variables

  • You can use volatile variables in concurrency operations like I mentioned above.
It warn, not to create a local copy of the variable in cache memories and always use the original value from main memory. Then only one value is there for many threads.

If you look at my Singleton Design pattern post, it can be seen double checked thread safe initialization of singleton design pattern. In this initialization we make the only instance as volatile.

  • Volatile variables are using to make double and long values atomically. 
You know that, both long and double primitives are 64bit. Some platforms make 64bit in two steps. This is not atomic. If you define variables with volatile, it makes that variables atomic.

  • Volatile boolean is used to terminate threads.
Volatile variable can be used as a flag. If you want to terminate a thread safety by using another thread, you can use this. Why you need volatile keyword is it will always get updated the status of the thread.

Look at the following example

package com.app.threads;

public class ThreadClose extends Thread {

   private volatile boolean stop = false;
 
   public void run() {
      while(!stop){
          System.out.println("Hi");
          closeThread();
      }
   }
 
   public void closeThread(){
      stop = true;
   }
}


Then you may ask why it uses volatile ? Simple answer is you need not to have synchronized block if you are using a volatile instance as I mentioned. 

Disadvantages of volatile

  • It may decrease your CPU performances.
Because it doesn't use cache memory, it always uses main memory. It is more valuable than accessing cache memory. Then it will decrease your system's performance.

But volatile keyword is less weight than using a synchronized block. Synchronized block required more CPU power than volatile. 

More about volatile

  • Volatile keyword can only be used with variables.
  • Volatile variable cannot be final.
  • Volatile object can be null.
  • There is no use of volatile keywords in non threaded applications.

Volatile vs Synchronized




Wednesday, July 27, 2016

REST web services

I think you may have an idea about web services on my previous post about SOAP. In this 
post I'm going to explain about REST.

History of REST

REST was created in 2000 by Roy Thomas Fielding in his PhD dissertation. 

Really what is REST ?

  • REST stands for REpresentational State Transfer
  • REST is an architectural design 
  • It is platform and language independent
  • REST uses HTTP for data transaction
  • REST doesn't contain any inbuilt security, session management and encryption features

REST vs SOAP

Look at the following request by SOAP

POST /InStock HTTP/1.1
Host: www.website.com
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.website.com/user">
  <m:GetUsername>
    <m:userName>Ann</m:userName>
  </m:GetUsername>
</soap:Body>

</soap:Envelope>


Look at the same request by REST

http://www.website.com/user/userName/Ann

Now you can understand how easy that SOAP is.


When to use REST ?

  • Social media servers
  • Mobile services
  • Web chat services
  • Other Social Media platforms

REST in  real life

  • Twitter API
  • Google glass API
  • Flicker 

Advantages of REST

  • Easy to implement and maintain.
  • Data can be manipulated in multiple formats (XML, JSON, XHTML, Plain text).
  • Light weight, fast and low bandwidth is required.
  • High scalability

Disadvantages of REST

  • Only work on top of HTTP protocol.
  • No inbuilt security and authentication mechanism.


Wednesday, July 20, 2016

Map interface



Map is used when you need  keyed elements. It means, Map stores your data with a key. This map concept is totally different from other collections like List, Set and Queue. There are four main implementations.
  1. HashMap
  2. LinkedHashMap
  3. HashTable
  4. TreeMap

Traverse on a Map

  • Using Iterator

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapDemo {

   public static void main(String[] args) {
  
      Map<Integer, Integer> map = new HashMap<>();
      map.put(1, 10);
      map.put(8, 50);
      map.put(5, 10);
      map.put(10, 90);
  
      Iterator<Integer> iterator = map.keySet().iterator();
  
      while (iterator.hasNext()) {
          Integer key = iterator.next();
          Integer value = map.get(key);
   
          System.out.print(key + "-");
          System.out.print(value + " ");
      } 
   }
}

  • Using enhanced for loop

for(Integer key : map.keySet()){
   Integer value = map.get(key);
   System.out.print(key + "-");
   System.out.print(value + " ");
}

Basic operations on Map interface


import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {

   public static void main(String[] args) {
  
       Map<Integer, Integer> map = new HashMap<>();
       map.put(1, 10);
       map.put(8, 50);
       map.put(5, 10);
       map.put(10, 90);
  
       System.out.println(map);
       System.out.println(map.isEmpty()); //check map is empty or not4
       System.out.println(map.size()); //get the size of the map
       System.out.println(map.keySet()); //get the keys
       System.out.println(map.values()); //get the values
       System.out.println(map.put(5, 100)); //replace value on given key
       System.out.println(map);
       map.clear(); //clear map
       System.out.println(map);
  
   }
}

You may look at the following code to understand how to use maps to find distinct words.


import java.util.HashMap;
import java.util.Map;

public class MapDemo {

 
   public static void main(String[] args) {
  
       Map<String, Integer> map = new HashMap<>();
       String statement = "If it is true this is also true and that is also ";
       String[] arr = statement.toLowerCase().split(" ");
  
       for(String s : arr){
           Integer i = map.get(s);
           map.put(s, (i==null) ? 1 : i+1);
       }
 
       System.out.println(map.size() + " distinct words : " + map);
    }
}


You may look at the following code to understand how to use maps to count characters in a String
import java.util.LinkedHashMap;
import java.util.Map;

public class StringOccurence {
    public static void main(String[] args) {
        String s = "easy java se";
        char[] chars = s.toCharArray();
 
        Map<Character, Integer> map = new LinkedHashMap<>();
        for(char c : chars){
            if(map.containsKey(c)){
                map.put(c, map.get(c)+1);
            }
            else{
                map.put(c, 1);
            }
        }
        System.out.println(map);
    }
}


HashMap vs LinkedHashMap vs HashTable vs TreeMap



 




Wednesday, July 13, 2016

Use of super keyword in Java


Super keyword is another important one. This is a reference variable which is used to call immediate parent class. This keyword is expensive when we talk about Inheritance and Polymorphism. There are three uses of super keyword. 
  1. super with variables
  2. super with constructors
  3. super with method overriding 

Super with variables

  • If you use super with instance variables, it will refer the variables of immediate parent class.
  • Look at the following example.
Parent.java

package com.app.superDemo;

public class Parent {
 
   String s = "Parent";
 
   public String showMessage() {
       return s;
   }
}


Child.java

package com.app.superDemo;

public class Child extends Parent {
 
   public String showMessage() {
       return super.s;
   }
}


Application.java

package com.app.superDemo;

public class Application {
 
   public static void main(String[] args) {
       Child child = new Child();
       System.out.println(child.showMessage());
   }
}


Super with constructors

  • We can use super keyword to invoke the constructor of immediate parent class 
  • Once you instantiate a class, the compiler calls the default constructor of that class.
Parent.java

package com.app.superDemo;

public class Parent {
   public Parent() {
       System.out.println("Parent");
   }  
}


Child.java

package com.app.superDemo;

public class Child extends Parent {

   public Child() {
       super();
       System.out.println("Child");
   }
}

Application.java

package com.app.superDemo;

public class Application {
 
   public static void main(String[] args) {
       new Child();
   }
}


Super with method overriding

  • If you want to call methods in parent class, you can use super keyword.
  • In overriding it will call child class method instead of parent class.
  • Look at the following example.
Parent.java

package com.app.inheritance;

public class Parent {

   public void ShowMessage(){
      System.out.println("Parent");
   } 
}


Child.java

package com.app.inheritance;

public class Child extends Parent {

   public void ShowMessage(){
       super.ShowMessage();
       System.out.println("Child");
   }
}

Application.java

package com.app.inheritance;

public class Application {
 
   public static void main(String[] args) {
       Child child = new Child();
       child.ShowMessage();
   }
}




Decorator Design Pattern



This is another design pattern that can be used to decorate an existing object without touching the structure of it. This is very useful design pattern.

Just a moment think about making a coffee. You can make a coffee and then you can add milk or egg as decorators for that existing coffee. It may give additional taste for your coffee. Decorator design pattern gives this approach in simple way.

Decorator design pattern shows how to do that thing in programming. Look at the following diagram to understand.




In this implementation there are few components that are very important to implement Decorator design pattern. I'm going to create a decorator for making a coffee.

  • Basic interface of coffee
  • Basic coffee
  • Coffee decorator
  • Milk coffee
  • Egg coffee
  • Client

Coffee.java

package com.app.design.decorator;

public interface Coffee {
    public String makeCoffee();
} 



BasicCoffee.java

package com.app.design.decorator;

public class BasicCoffee implements Coffee{
    public String makeCoffee(){
        return "Normal coffee";
    }
}



CoffeeDecorator.java

package com.app.design.decorator;

public abstract class CoffeeDecorator implements Coffee {

   protected Coffee coffee;
 
   public CoffeeDecorator(Coffee coffee){
       this.coffee = coffee;
   }
 
   @Override
   public String makeCoffee(){
       return coffee.makeCoffee();
   }
}



MilkCoffee.java

package com.app.design.decorator;

public class MilkCoffee extends CoffeeDecorator {
   public MilkCoffee(Coffee coffee) {
       super(coffee);
   }
 
   public String makeCoffee(){
       return coffee.makeCoffee() + " Milk";
   }
}



EggCoffee.java

package com.app.design.decorator;

public class EggCoffee extends CoffeeDecorator {
    public EggCoffee(Coffee coffee) {
       super(coffee);
    }
 
    public String makeCoffee(){
       return coffee.makeCoffee() + " Egg";
    }
}



Client.java

package com.app.design.decorator;

public class Client {
    public static void main(String[] args){
  
        Coffee coffee = new BasicCoffee();
        System.out.println(coffee.makeCoffee());
  
        Coffee milkCoffee = new MilkCoffee(new BasicCoffee());
        System.out.println(milkCoffee.makeCoffee());
  
        Coffee eggCoffee = new EggCoffee(new BasicCoffee());
        System.out.println(eggCoffee.makeCoffee());
  
        Coffee milkEggCoffee = new EggCoffee(new MilkCoffee(new BasicCoffee()));
        System.out.println(milkEggCoffee.makeCoffee());
    }
}




You may look at both class diagram and these classes. When you run this program, you will be able to see it is very easy to decorate basic coffee with this implementation.

Advantages of Decorator class

  • It is easy to adding new behaviors at run time without compiling the code.
  • Provide flexible approach than inheritance when changing behaviors of objects.

Disadvantages of Decorator class

  • Create many objects
  • Complex to debug code (Because, functions are added in run time)

When it uses in Java ?

  • Decorator is used in Java IO package
    • java.io.BufferedReader
    • java.io.FileReader
    • java.io.Reader

Wednesday, June 29, 2016

Factory Design pattern

This is another most important design pattern and this is the foundation of Spring, Struts and most of frameworks. Specially this is mostly used in JDK also.

The main advantage of using this method is to hide implementation details from the user. Actually this design pattern is developed using Encapsulation concept. It decouples calling from target class.  Look at the following class diagram and example to understand about Factory design pattern.


Look at this example with above diagram.

Animal.java interface

package com.app.designs.factory;

public interface Animal {
    public void eat();
}



Cat.java class

package com.app.designs.factory;

public class Cat implements Animal {

   @Override
   public void eat() {
       System.out.println("Cat eating"); 
   }
}



Dog.java class

package com.app.designs.factory;

public class Dog implements Animal {

   @Override
   public void eat() {
       System.out.println("Dog eating");
   }
}



AnimalFactory.java class

package com.app.designs.factory;

public class AnimalFactory {

   public Animal buildAnimal(String animalType){
  
      if(animalType==null){
          return null;
      }
      if("dog".equalsIgnoreCase(animalType)){
          return new Dog();
      }
      if("cat".equalsIgnoreCase(animalType)){
          return new Cat();
      }
      return null;
   }
}



Application.java class

package com.app.designs.factory;

public class Application {

   public static void main(String[] args) {
      String animalType = "cat";
  
      AnimalFactory factory = new AnimalFactory();
      Animal animal = factory.buildAnimal(animalType);
      animal.eat();
   }
}




In this example I want to create a cat instance. Then you will be able to see it creates a new Cat object. If you want a Dog object, you need to set animalType to dog. Then it will create a new Dog object. According to the user requirement, system will produce the requested abject. 

This is the core concept behind Spring and Struts frameworks. You may know that there is a concept behind Spring framework called "Dependency Injection". To make it loosely coupled, it uses this factory design pattern inside the framework.


Advantages of Factory design pattern

  • Make code loosely coupled 
  • Hide implementation details from outside

Disadvantages of Factory design pattern

  • It looks your code is more abstract
  • Code becomes complex


Thursday, June 23, 2016

Set interface


This is another core interface in java collection hierarchy. Special thing is Set cannot contain duplicates. Set has three main implements.

  1. java.util.TreeSet
  2. java.util.HashSet
  3. java.util.LinekedHashSet

Common characteristics

  • No duplicates
  • Not thread safe

Other characteristics

  • HashSet is the fastest set implementation, TreeSet is slowest one.
  • HashSet doesn't maintain a order. But LinkedHashSet maintain insertion order while TreeSet maintain sorted order because it implements sortedSet interface.
  • Both HashSet and LinkedHashSet allow null values but TreeSet doesn't allow null values.
  • LinkedHashSet was introduced in 1.4 version in Java.

TreeSet vs HashSet vs LinkedHashSet




Look at the following example to understand about Treeset. It shows about sorting of TreeSet. 

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {

   public static void main(String[] args) {
  
       Set<Integer> treeSet = new TreeSet<>();
  
       treeSet.add(30);
       treeSet.add(10);
       treeSet.add(50);
       System.out.println(treeSet);
   } 
}



Look at the following example to get a brief idea about set interface.

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {

   public static void main(String[] args) {
  
       Set<Integer> treeSet = new TreeSet<>();

  
       treeSet.add(30);
       treeSet.add(10);
       treeSet.add(50);
       System.out.println(treeSet);
  
       System.out.println(treeSet.size());
       System.out.println(treeSet.isEmpty());
       System.out.println(treeSet.contains(500));
       System.out.println(treeSet.remove(10));
       System.out.println(treeSet.equals(50));
       treeSet.clear();
       System.out.println(treeSet);
   }
}



Look at the following example to get an idea about the things that you can do with sets. Following example shows to get distinct characters.

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {

   public static void main(String[] args) {
  
       Set set = new TreeSet<>();
  
       String s = "This is a set interface";
       String []arr = s.split("");
  
       for(String i : arr){
           set.add(i);
       }
  
       System.out.println(set);
   }
}




Wednesday, June 22, 2016

List interface



In my first post of collection you may have an idea about, how to choose a collection. In this post I'm gonna talk about List interface.

List interface can be used if you need an ordered collection which can also have duplicates. There are four special classes which implement List interface.
  1. java.util.ArrayList
  2. java.util.LinkedList
  3. java.util.Vector
  4. java.util.Stack

ArrayList

  • Implemented by using a re-sizable array (Dynamic array).
  • It can contain duplicates.
  • ArrayList is not synchronized .
  • Maintain insertion order.
  • Default initial capacity is very small. Once it is filled its size will be incremented by 50%.
  • It allows random access and it is fast. But Inserting and deleting is slow.
  • This uses iterator to traverse.

LinkedList

  • Implemented by using doubly LinkedList
  • Duplicates are allowed.
  • LinkedList is not synchronized.
  • Maintain insertion order.
  • LinkedList allows sequential access and it slow, but inserting and deleting is fast.
  • LinkedList doesn't have initial size.
  • Compare to ArrayList and Vector, LinkedLIst uses more memory.

Vector

  • Vector looks same as ArrayList.
  • Main difference is, Vector is synchronized.
  • Accessibility is slow, because Vector is synchronized.
  • Once it is filled, initial capacity is incremented by 100%.
  • Vector uses Enumeration to traverse.

Stack

  • This is another simple class which is extended to Vector class.
  • Stack is Last In First Out (LIFO) manner collection.
  • Stack is also synchronized just like Vector, then Stack is also slow.
  • Stack has few special methods, push(), pop() and peek().
Look at the following example about simple operations of Stack.

import java.util.Stack;

public class StackDemo {

   public static void main(String[] args) {
  
       Stack<Integer> stack = new Stack<>();
       stack.push(10);
       stack.push(30);
       stack.push(20);
       stack.push(50);
  
       System.out.println(stack);
       stack.pop();
       System.out.println("After pop : " + stack);
       System.out.println("Head of stack : " + stack.peek());
    }
}




Vector and Stack was introduced in 1.0 version while ArrayList, LinkedList and Collection was introduced in 1.2 version of Java. Because of that, Vector and Stack is called "legacy classes".


You may look at the following example to get an idea about List interface. This example is done by using ArrayList and it can be implemented by using LinkedList and also using a Vector.


public class ArrayListDemo {
 
   public static void main(String[] args) {
  
      List<Integer> list = new ArrayList<>();
      List<Integer> list2 = new ArrayList<>();
  
      list.add(10); //add element to the list
      list.add(20);
      list.add(30);
      list.add(30);
      list.add(0, 100); //add element to given index
      System.out.println(list);
  
      list.remove(1); //remove the element from given index
      System.out.println(list.isEmpty()); //check the list is empty or not
      System.out.println(list.size()); //get the size of list
      System.out.println(list.contains(30)); //check given value is there in list
      System.out.println(list.indexOf(30)); //give index of given value
      System.out.println(list.get(2)); //get value of given index
      System.out.println(list.equals(list2)); //compare two lists
      System.out.println(list.lastIndexOf(100)); //return last index of given value
      System.out.println(list.lastIndexOf(70)); //if not return -1
      System.out.println(list);
  
      list.set(0, 200); //set value to given index
      System.out.println(list);
  
      list.clear(); //clear list
      System.out.println(list);
   } 
}


Using Iterator to traverse

  • Iterator can be used to traverse on ArrayList and LinkedList.
  • You can also use loops to traverse.
  • Look at the following example.

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class ListSpecialMethods {

   public static void main(String[] args) {
  
       List<Integer> linkedList = new LinkedList<>();
       linkedList.add(10);
       linkedList.add(20);
       linkedList.add(30);
       linkedList.add(10);
       linkedList.add(60);
       linkedList.add(80);
  
       showData(linkedList);
   }
  
 
   public static <E> void showData(List<E> list){
       Iterator<E> iterator = list.iterator();
  
       while(iterator.hasNext()){
            System.out.print(iterator.next() + " ");
       }
   }
}

ArrayList vs LinkedList vs Vector vs Stack



RandomAccess interface

  • This is very important when talking about ArrayList and Vector classes.
  • These two classes implements RandomAccess interface.
  • RandomAccess interface is a Marker interface like Serializable and Cloneable interfaces. There is no methods present in these marker interfaces.
  • These interfaces identify classes with the capability of they are defined.

Now you know both ArrayList and Vector classes implement RandomAccess interface. So when you searching and accessing any data inside of ArrayList or Vector, it is too fast than others.




Tuesday, June 21, 2016

Collection interface



Collection interface is the core interface of List, Queue and Set. It consist of core operations that can be used to work with above interfaces.

Basic methods of Collection interface



You may look at the following example which is done using List interface.

package com.app.collections;

import java.util.LinkedList;
import java.util.List;

public class CollectionDemo {

   public static void main(String[] args) {
 
      List list1 = new LinkedList<>();
      List list2 = new LinkedList<>();
  
      list1.add("Apple");
      list1.add("Mango");
      list1.add("Banana");
      System.out.println("List 1 : " + list1);
  
      list2.addAll(list1);
      list2.add("Woodapple");
      System.out.println("List 2 : " + list2);
  
      list2.retainAll(list1);
      System.out.println("List 2 : " + list2);
  
      list2.remove("Apple");
      System.out.println("List 2 : " + list2); 
  
      System.out.println("isEmpty()     : " + list2.isEmpty());
      System.out.println("size()        : " + list2.size());
      System.out.println("hashCode()    : " + list2.hashCode());
      System.out.println("equals()      : " + list2.equals("Apple"));
      System.out.println("contains()    : " + list2.contains("Apple"));
      System.out.println("containsAll() : " + list1.containsAll(list2));
  
      list1.clear();
      System.out.println("clear() : " + list1);
 
   }

}




I think now you have a basic idea of using Collection interface.

Traverse on a collection

There are three main ways to traverse on a collection.
  1. Using loops
  2. Using iterators
  3. Using streams
Third concept is a new one which is introduced after Java 8. At the moment I skip it and looking through first and second ways. Look at the following example.

package com.app.collections;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class CollectionTraverse {

    public static void main(String[] args) {
  
        List list = new LinkedList<>();
  
        list.add("Apple");
        list.add("Mango");
        list.add("Banana");
        list.add("Woodapple");
  
        //Just print the list
        System.out.println(list);
  
  
        //Using a while loop
        int i = 0;
        while(i < list.size()){
            System.out.print(list.get(i) + " ");
            i++;
        }
        System.out.println();
  
  
        //Using a for loop
        for (int j=0; j < list.size(); j++) {
            System.out.print(list.get(j) + " ");
        }
        System.out.println();
  
  
        //print using foreach loop
        for(String s : list){
             System.out.print(s + " ");
        }
        System.out.println();

  
        //print using iterator
        Iterator iterator = list.iterator();
  
        while(iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
        System.out.println();

  
        //print using Java 8 foreach loop
        list.forEach(name -> System.out.print(name + " "));
        System.out.println();

    }
}



Serializable interface

This is another important thing when you think about Collection interface. I think you may heard about serialization. Serialization is the process of convert the object into byte stream. Why we need to do this ?

  • To stream through a communication link (One JVM to another)
  • Save data in persistence storage
This is very important for collection framework. Each and every collection class implements Serializable interface by default.

Cloneable interface

This is another important interface which each and every Collection classes are implemented. Cloneable interface is used to get a exact clone of objects for future needs. 

Just think once you got a list of objects, you want to manage it. While you are doing this, sometimes objects may be lost. At the time you'll have to get that list of objects again from the source. But you don't need to worry about this, because every Collection class is implemented Cloneable interface and it can be easily get the same set of objects again.




Queue interface



Queue is another interface which implements Collection interface. This follows First In First Out (FIFO) manner in implementation. This interface has some special methods that can be used to work with it.

Implementing a queue

A queue can be implemented as follows.
  1. Using a LinkedList (java.util.LinkedList)
  2. Using a ProrityQueue (java.util.ProrityQueue)
  3. Using Java concurrency utilities (java.util.concurrent)

Special thing is, a queue which is implemented using Java concurrent package are bounded, others are unbounded. LinkedList is a better approach to implement a queue. Look at the following code to have an idea about queue.

    Queue priorityQueue = new PriorityQueue();
    Queue linkedListQueue = new LinkedList();


If you use a LinkedList to implement a queue, then specially you can add null values also. But it your are using a PriorityQueue, you cannot add null values.

There are some special methods that can be used with a queue. Look at the following methods and at the bottom you can see an example using these methods.

add() vs offer()

  • Both methods can be used to add elements to the queue.
  • But in PriorityQueue, you cannot add null values. It will throw NulPointerException. 
  • But you can add null values in LinkedList implementation of queue. 
  • Main difference can be seen when it happens any error while adding(Capacity exceeding).
  • At the time add() method throws IllegalStateException but offer() method returns false

    Queue<Integer> priorityQueue = new PriorityQueue<>();
    Queue<Integer> linkedListQueue = new LinkedList<>();
  
//  priorityQueue.add(null);
//  priorityQueue.offer(null);
    priorityQueue.add(10);
    priorityQueue.add(20);
    priorityQueue.offer(100);
    priorityQueue.offer(200);  
    System.out.println(priorityQueue);
  
    linkedListQueue.add(22);
    linkedListQueue.add(77);
    linkedListQueue.offer(33);
    linkedListQueue.add(null);
    linkedListQueue.offer(null);
    System.out.println(linkedListQueue);


remove() vs poll()

  • Both methods are used to return the head and remove it.
  • If queue is empty, remove() method throws NoSuchElementException but poll() method returns null.

    priorityQueue.remove();
    linkedListQueue.remove();
  
    priorityQueue.poll();
    linkedListQueue.poll();


element() vs peek()

  • Both methods are used to return the head of the queue.
  • If queue is empty element() methods throws NoSuchElementException but peek() method returns null.

    priorityQueue.element();
    linkedListQueue.element();
  
    priorityQueue.peek();
    linkedListQueue.peek();



Look at the following code which is implemented using a PriorityQueue for a complete reference.

import java.util.PriorityQueue;
import java.util.Queue;

   public class QueueDemo {

       public static void main(String[] args) {
  
           Queue<Integer> priorityQueue = new PriorityQueue<>();
  
           priorityQueue.add(10);
           priorityQueue.add(20);
           priorityQueue.offer(100);
           priorityQueue.offer(200);  
           System.out.println(priorityQueue);

           System.out.println("Remove head using remove()  :" + priorityQueue.remove());
           System.out.println(priorityQueue);
           System.out.println("Remove head using poll()    : " + priorityQueue.poll());
           System.out.println(priorityQueue); 

           System.out.println("Return head using element() : " + priorityQueue.element());
           System.out.println("Return head using peek()    : " + priorityQueue.peek());
  
           priorityQueue.removeAll(priorityQueue);
           System.out.println(priorityQueue);
  
           System.out.println(priorityQueue.poll());
           System.out.println(priorityQueue.peek());
//         System.out.println(priorityQueue.remove());
//         System.out.println(priorityQueue.element());
  
     }
}




The basics of Collection in Java



Collection, this may be another most advanced section in Java. I think you may heard that there are so many things to learn about Collections. Lets begin our journey.


What is the Collection & Collection framework ?

  • Collection is a just a collection of objects or data.
  • Java collection framework is a architecture which is used to manage collections in Java.
  • Java Collection framework is consist of interfaces, implementations and also algorithms.

Core collection interface hierarchy


As you can see, Map is a separate collection interface. Because it stores values with a key.

Advanced collection hierarchy


Click on image for clear view


Click on image for clear view

How to select which Collection is needed ?

Collection hierarchy is a big one, but you can identify it easily. Look at the following diagram. Begin with the blue color checking statement.


Click on image for clear view


Collection vs Collections

  • Collection is a interface and it is the root interface of Java Collection framework.
  • Coillections is a utility class which is from java.util package.
  • Collections class consist of core methods that can be used commonly with List, Set and Queue. 
  • There are so many methods which are defined in Collections class.

List vs Set vs Queue vs Map

Click on image for clear view








Advantages of using Collection framework 

  • No need to learn new APIs or create new APIs.
  • Increase speed and interoperability.
  • Reduce programming effort.
  • It increase software reuse. 




Friday, June 17, 2016

Singleton Design pattern


What is a design pattern ?

  • In simple words, design patterns are best practices in software developing field.
  • These design patters are invented by well experienced Object Oriented Software developers using their practice and experience.

Singleton design pattern

  • This design pattern can be used to control object creation of software development life cycle.
  • If you use Singleton design pattern, then you can have only one instance of that type.

How to create a Singleton object ?

  • Create private constructor (Then no one can instantiate this class, it means others can't create objects)
  • Create the only one private static instance
  • Create a public method to invoke this instance

Types of singleton implementations

There are several ways to implement a singleton class.
  1. Eager initialization
  2. Static block initialization
  3. Lazy initialization
  4. Thread safe initialization
  5. Enum initialization

Eager initialization

  • In this method, the instance is created at the time of class loading.
  • Instance is created even client is requesting or not.

public class Singleton{

    private static final Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton getInstance() {
       return instance;
    }
}


Static block initialization

  • This is very same as Eager initialization.
  • Special thing is, we use static block in getInstance() method to have exception handling.

public class Singleton{

    private static Singleton instance;

    private Singleton() { }

    static{
        try {
            instance = new Singleton(); 
        }catch (Exception e) {
            System.out.println("Error : " + e);
        }
    }
 
    public static Singleton getInstance(){
        return instance;
    }
}


Lazy initialization

  • This is a good one in single threaded environment.
  • But in multithreaded environment, we have to use thread safe initialization.

public class Singleton{

    private static Singleton instance;

    private Singleton() { }

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


Thread safe initialization

  • This is just very similar to Lazy initialization.
  • But here synchronize the method that can be used to get the instance in multi threaded environment.

public class Singleton{

    private static Singleton instance;

    private Singleton() { }

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

I think you can remember, I have mentioned something called doubled check in thread section. In this method, it is used a synchronized block. Here you can see how to implement this.

public class Singleton {

    private volatile static Singleton instance;

    private Singleton() { }
    
    public static Singleton getInstance() { 
        if (instance == null) {
             synchronized (Singleton.class) {
                  if (instance == null) {
                        instance = new Singleton();
                  }
             }
        }
        return instance;
    }
}


Enum initialization

This is very efficient way to implement a singleton. Because it is very easy to write. Here is the way to implement it.

public enum EnumSingleton{
      instance;
}

You can get the instance by calling EnumSingleton.instance

Which is the best one ?

Enum singleton implementation is the best way, because it is very easy to implement and use. But this is available since Java 5.

When to use Singleton design pattern ?

  • To manage shared resources(Database connections, file manager)
  • Logging
  • Catching

Singleton in JDK

There are many singleton classes that can be found in JDK. I listed three of them.
  • In java.lang.Runtime which provides getRuntime() method.
  • In java.awt.Toolkit which provides getDefaultToolkit() method.
  • In java.awt.Desktop which provides getDesktop() method.

Use of Singleton pattern when creating a database connection


package com.app.design.singleton;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Singleton {

   private static Singleton instance;
   private static Connection connection;
 
   private Singleton(){
  
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://localhost:3306/database";
      String username = "username";
      String password = "password";
  
      try{
          Class.forName(driver);
              try{
                  connection = DriverManager.getConnection(url, username, password);
              }catch(SQLException e){
                  e.getMessage();
              }
      }catch(ClassNotFoundException e){
          e.getMessage();
      }
   }
 
   public static Singleton getInstance(){
  
      if(instance == null){
          synchronized (Singleton.class){
             if(instance == null){
                 instance = new Singleton();
             }
          }
      }
      return instance;
   }
 
}