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.If you want to know about that Lock of object, please refer this post.

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. More info

  • 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 (More about variables).
  • 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 (More about constructors)
  • 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