Friday, 27 June 2014

@Target

@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.

Lets see it by an Example.

import java.lang.annotation.*;

@Target (value = {ElementType.FIELD, ElementType.CONSTRUCTOR})
@interface DocumentMe{

}

To Know about ElementType read the below link.

We can apply Annotation DocumentMe to any field and constructors of a class. But if you tries to apply it to any thing other than field and constructor, compiler throws error.

class TargetTest{
 @DocumentMe
 int field1;
 
 @DocumentMe
 TargetTest(){
 
 }
 
 @DocumentMe
 int method1(){
 
 }
}

When you tries to compile the above program, compiler throws below error. Since DocumentMe can't be applied to methods.

TargetTest.java:10: error: annotation type not applicable to this kind of declar
ation
        @DocumentMe
        ^
1 error

1. It is a compile-time error if the same enum constant appears more than once in the value element of an annotation of type java.lang.annotation.Target.



 
Prevoius                                                 Next                                                 Home

Thursday, 26 June 2014

Singleton Design Pattern

singleton pattern restricts the instantiation of a class to one object. That is you can't create more than one object to this class. This is useful when exactly one object is needed to coordinate actions across the system.

Will see various approaches to construct singleton class and see the problems in them. Finally finds better solution.

Approach 1
Make the default constructor as private and create static instance inside the class itself. Provide a static getter method to get the instance of this class.

class SingleTon{
 static SingleTon instance = new SingleTon();
 
 private SingleTon(){
 
 }
 
 public static SingleTon getInstance(){
  return instance;
 }
}

Constructor for the SingleTon class has private access, so it can't be accessed from outside. 'getInstance' method simply the instance which is already created.

class SingleTonTest{
 public static void main(String args[]){
  SingleTon obj1 = SingleTon.getInstance();
  SingleTon obj2 = SingleTon.getInstance();
  System.out.print("Is obj1 and obj2 points to same object ");
  System.out.println((obj1==obj2));
 }
}

Output
Is obj1 and obj2 points to same object true

Problem in Approach 1
Object is created, even if needs or not. If this Object is resource intensive and if your Application never used it, then it is wastage of your resource.

Approach 2
Create the instance when needed. While creating an instance check whether instance already exist or not. If instance is not there, then create one and return it, else return the existing one.

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

class SingleTonTest{
 public static void main(String args[]){
  SingleTon obj1 = SingleTon.getInstance();
  SingleTon obj2 = SingleTon.getInstance();
  System.out.print("Is obj1 and obj2 points to same object ");
  System.out.println((obj1==obj2));
 }
}

Output
Is obj1 and obj2 points to same object true

Problem in Approach 2
In a Multi threaded Environment, Above code won't work.

Lets take a scenario, there are two threads t1 and t2 calls the getInstance method. Lets us assume, t1 got a chance first to enter into getInstance method, After checking for the condition(instance == null) which is true, it swapped out, and t2 come in, now for t2 also the condition (instance == null) is true, so there are two instances got created.

For Example, let us update the program to support threads.

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

class SingleTonTest extends Thread{
 SingleTon obj;
 
 public void run(){
  obj = SingleTon.getInstance();
 } 
 
 public static void main(String args[])throws Exception{
  SingleTonTest t1 = new SingleTonTest();
  SingleTonTest t2 = new SingleTonTest();
  
  t1.start();
  t2.start();
  
  t1.join();
  t2.join();
  
  System.out.print("Is t1.obj and t2.obj point to same object ");
  System.out.println((t1.obj==t2.obj));
 }
}

On Multiple runs the output is like below.

Run 1:
Is t1.obj and t2.obj point to same object false

Run 2:
Is t1.obj and t2.obj point to same object false

Run 3:
Is t1.obj and t2.obj point to same object false

Run 4:
Is t1.obj and t2.obj point to same object true

Run 5:
Is t1.obj and t2.obj point to same object true

Run 6:
Is t1.obj and t2.obj point to same object false

Approach 3
To solve the above problem, why can't we use synchronization. Looks like a good idea. Now change the code like below.

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

class SingleTonTest extends Thread{
 SingleTon obj;
 
 public void run(){
  obj = SingleTon.getInstance();
 } 
 
 public static void main(String args[])throws Exception{
  SingleTonTest t1 = new SingleTonTest();
  SingleTonTest t2 = new SingleTonTest();
  
  t1.start();
  t2.start();
  
  t1.join();
  t2.join();
  
  System.out.print("Is t1.obj and t2.obj point to same object ");
  System.out.println((t1.obj==t2.obj));
 }
}

Output
Is t1.obj and t2.obj point to same object true

Problem in Approach3
Don't you felt synchronization is a costliest process. If one thread acquire the lock on the class SingleTon, then remaining all thread must wait. So it is not effective solution.


Final Solution
Use double checked locking. First check whether the instance is null or not, then take the lock if the instance is null, else return the instance.

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






                                                             Home

Why Synchronization is costly operation

Synchronization is costly operation, because it contains overhead of acquiring and releasing of locks and other thread has to wait until the lock hold is released.

Below program, which will simply iterate a loop 1000000000 times
class WithOutSynchronization implements Runnable{
      public void run(){
         sum();
      }

      public void sum(){
         for(int i=0; i < 1000000000; i++){
         }
      }

      public static void main(String args[]) throws Exception{
         WithOutSynchronization task1 = new WithOutSynchronization();
         Thread t1 = new Thread(task1);
         Thread t2 = new Thread(task1);

         long time1 = System.currentTimeMillis();
         t1.start();
         t2.start();
         t1.join();
         t2.join();
         long time2 = System.currentTimeMillis();

         System.out.println("Time taken is " + (time2-time1));
      }
   }
   

Output
Time taken is 5

will modify the above program, by applying synchronization
  class WithSynchronization implements Runnable{
      public void run(){
         sum();
      }

      public void sum(){
         for(int i=0; i < 1000000000; i++){
            synchronized(this){
            }
         }
      }

      public static void main(String args[]) throws Exception{
         WithSynchronization task1 = new WithSynchronization();
         Thread t1 = new Thread(task1);
         Thread t2 = new Thread(task1);

         long time1 = System.currentTimeMillis();
         t1.start();
         t2.start();
         t1.join();
         t2.join();
         long time2 = System.currentTimeMillis();

         System.out.println("Time taken is " + (time2-time1));
      }
   }
 

Output
Time taken is 18014

Compare the two outputs, for the first program with out synchronization takes 5 milliseconds to execute, with synchronization takes 18014 milliseconds to execute.




                                                 Home

Interface : static Methods

In addition to default methods, you can define static methods in interfaces. All method declarations in an interface, including static methods, are implicitly public.
interface A{
 void print();
 
 static void show(){
  System.out.println("I am in interface A");
 }
 
}

interface B extends A{
 void display();
 static void show(){
  System.out.println("I am in interface B");
 }
}

class Test{
 public static void main(String args[]){
  B.show();
  A.show();
 }
}

Output
I am in interface B
I am in interface A



Prevoius                                                 Next                                                 Home

Extending Interfaces That Contain Default Methods

When you extend an interface that contains default methods you have 3 possibilities.

1. If interface 'B' extend interface 'A', and not providing the implementations for default methods in A, then extended interface 'B' inherit the default method.
interface A{
 void print();
 
 default void show(){
  System.out.println("I am in show");
 }
}

interface B extends A{
 void display();
}

class C implements B{
 public void display(){
 }
   
 public void print(){
 }
}

class Test{
 public static void main(String args[]){
  C obj1 = new C();
  obj1.show();
 }
}

Output
I am in show

2. If interface 'B' extend interface 'A', and re-declare the default methods, then default methods became abstract.
interface A{
 void print();
 
 default void show(){
  System.out.println("I am in show");
 }
}

interface B extends A{
 void display();
 void show();
}

Now any class that is going to implement the interface B, has to provide the implementation for the method show also.

class C implements B{
 public void display(){
 }
   
 public void print(){
 }
}

When you tries to compile the above program compiler throws below error, since class 'C' is not providing the implementation for the method 'show'.

C.java:1: error: C is not abstract and does not override abstract method show()in B
class C implements B{
^
1 error

To make the program works fine, add the implementation for the method 'show' in the class 'C'.

class C implements B{
 public void display(){
 }
   
 public void print(){
 }
 
 public void show(){
  System.out.println("I am in show");
 }
}

class Test{
 public static void main(String args[]){
  C obj1 = new C();
  obj1.show();
 }
}

Output
I am in show

3. If interface 'B' extend interface 'A', and redefine the default methods, then default methods are overridden.
interface A{
 void print();
 
 default void show(){
  System.out.println("I am in interface A");
 }
}

interface B extends A{
 void display();
 default void show(){
  System.out.println("I am in interface B");
 }
}

class C implements B{
 public void display(){
 }
   
 public void print(){
 }
}

class Test{
 public static void main(String args[]){
  B obj1 = new C();
  A obj2 = obj1;
  
  obj2.show();
 }
}

Output
I am in interface B



Prevoius                                                 Next                                                 Home

Interface : Default Methods

Default methods enables to add new functionality to the existing interfaces, and ensure binary compatibility with code written for older versions of those interfaces.

By using default keyword you can specify a default implementation for a method in interface. All method declarations in an interface, including default methods, are implicitly public.

Example
interface Car{
 void swim();
 void drive();
}

class MyCar implements Car{
 public void swim(){
  System.out.println("I can swim");
 }
 
 public void drive(){
  System.out.println("I can Drive");
 }
}
Lets suppose, the Car interface adds new functionality like that all cars can fly.A new abstract method 'fly' added to Car interface like below.

interface Car{
 void swim();
 void drive();
 void fly();
}

Previously MyCar class implemented the Car interface, now with this updated version of Car interface, if you tries to compile MyClass.java, compiler throws below error since, MyCar is not providing implementation for 'fly'.

MyCar.java:1: error: MyCar is not abstract and does not override abstract method
 fly() in Car
class MyCar implements Car{
^
1 error

Here default methods plays a role to ensure binary compatibility with code written for older versions of those interfaces.

interface Car{
 void swim();
 void drive();
 default void fly(){
  System.out.println("I Can Fly");
 }
}

We are providing default implementation for the fly method in Car interface. So it makes your previously existed classes which implements Car interface works fine.

class MyCar implements Car{
 public void swim(){
  System.out.println("I can Swim");
 }
 
 public void drive(){
  System.out.println("I can Drive");
 }
}

class CarTest{
 public static void main(String args[]){
  MyCar car1 = new MyCar();
  
  car1.swim();
  car1.drive();
  car1.fly();
 }
}

Output
I can Swim
I can Drive
I Can Fly



Prevoius                                                 Next                                                 Home

Java8 Enhancements to Interface

Java8 added new features to interfaces, that you can provide default method implementations to interfaces using default keyword, and you can add static methods also.



Prevoius                                                 Next                                                 Home