Thursday, 11 September 2014

Java design pattern - Singleton



Singleton design pattern is the most useful pattern in real time scenario.Singleton pattern will ensure that there is only one instance of a class is created in the JVM.This implementation restrict the user to create multiple access point or instance. This is a creational design pattern. It has many implementation over java language, but singleton is an anti-pattern or bad practice.



There is 2 basic way for implementing singleton behavior.

  • 1.       Eager/Early Loading
  • 2.       Lazy Loading

Eager/Early Loading


Eager/Early loading is basically load of objects before actually use. But, sometimes it’s not recommended, if the object creation is expensive.


A simple example of eager or early loading.



/**
 * Eager/Early Loading
 * @author javalang
 *
 */
public class SingleTon {

private static final SingleTon OBJSINGLETON=new SingleTon();

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw new IllegalStateException("This is singleton, object already exist");
};

public static SingleTon getInstance(){
      return OBJSINGLETON;
}

}



Lazy Loading


Lazy loading means the object will be load when it’s required. When we need the object that time only we need to create object. It’s useful and recommended. But the use of singleton is depends on the context or requirement. It’s always recommended when the operation is really expensive.

A simple example of lazy loading.


packagecom.jdeveloperguide.lab;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon {

private static SingleTon OBJSINGLETON=null;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Call this method & create object only when required
public static SingleTon getInstance(){
      if(OBJSINGLETON==null){
            OBJSINGLETON=new SingleTon();
      }
      return OBJSINGLETON;
}

}



But, in the above example the singleton object is not useful for multi-threaded 
environment. This above singleton objects are not thread safe. 
You can use ‘synchronized’ keyword to make the object creation thread safe.
 
A simple example with synchronized keyword.
 

packagecom.jdeveloperguide.lab;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon {

private static SingleTon OBJSINGLETON=null;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Call this method & create object only when required
public static SingleTon getInstance(){
            synchronized (SingleTon.class) {
                  OBJSINGLETON=new SingleTon();
            }          
      return OBJSINGLETON;
}
} 




In the above example the synchronized block allow the object creation thread safe. But the member variable is not thread safe yet. The member variable OBJSINGLETON is not thread safe here. 


Here is one important question for interview. How to make a variable thread safe?


Ans : By using volatile keyword.



But, there is one another better approach which will help us to cross check the implementation. By implementing the “Double-checked locking” we can make the singleton object more secure. This ensure the expensive operation of creating object is the very first call. 

packagecom.jdeveloperguide.lab;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon {

private static volatile SingleTon OBJSINGLETON=null;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Create object only when required
public static SingleTon getInstance(){
      //1st Check
      if(OBJSINGLETON==null){
            synchronized (SingleTon.class) {
                  //2nd Check
                  if(OBJSINGLETON==null)
                  OBJSINGLETON=new SingleTon();
            }          
      }
      return OBJSINGLETON;
}
}


Now the singleton object OBJSINGLETONis thread safe. But, there is one more issue with singleton when we go for serialization. Because, during deserialization process it creates new object and it violate the singleton strategy. So, we should make sure that there is no new objects are created during deserialization. To avoid this issue you can use readResolve() method in serializable.



A simple example using readResolve() method.

packagecom.jdeveloperguide.lab;

importjava.io.Serializable;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon implements Serializable {

private static volatile SingleTon OBJSINGLETON=null;
public static final long serialVersionUID=0L;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Create object only when required
public static SingleTon getInstance(){
      //2nd Check
      if(OBJSINGLETON==null){
            synchronized (SingleTon.class) {
                  //2nd Check
                  if(OBJSINGLETON==null)
                  OBJSINGLETON=new SingleTon();
            }          
      }
      return OBJSINGLETON;
}

//This ensure the protection on serialization
@SuppressWarnings("unused")
private SingleTon readResolve(){
      return OBJSINGLETON;
}
}


 All the above example with implementations are traditional , which are not recommended by java 5 and above. There is one more better way to implement singleton strategy by using Enum.

A simple example using Enum.


packagecom.jdeveloperguide.lab;

/**
 * Singleton behavior using Enum
 * @author jdeveloperguide
 *
 */
public enum SingleTonEnum {
SINGLETONINSTANCE;
public voidjavaProgrammingStuff(){
      //Here is your stuffs
}
}


Enum provides lazy loading approach. Enum gives guaranty for thread safety and safety during serialization.

 



               

Interview Questions :


Q – What is serialVersionUID ?

Ans :- This maintain version number in complied class. It’s useful during deserialization process. During deserialization it maintains the similar copy as similar as serialization process.


Q – What is readResolve() method ?

Ans :- This method ensure a unique object during deserialization. It’s useful when implementing serialization over singleton object. It avoid to create new object during deserialization.




 Hope it will help you.

Wednesday, 10 September 2014

Git plugin installation on Eclipse

Step by step process to install git  plugin on eclipse .

Step 1) Use the repository location. i.e. http://download.eclipse.org/egit/updates

Step 2.) Go to Help > Install New Software

Step 3.) Add repository location, Click Add. Enter repository name as "EGit".Then click Ok to add repository location.

Step 4.) Expand “Eclipse Git Team Provider” and select “Eclipse Git Team Provider”. Then Click Next

Step 5.) Review product and click Next.

Step 6.) Accept the agreement and click Finish.

Step 7.) Then, it will take few time for download the plugin and binaries.

Step 8.) Then ,accept the prompt to restart the Eclipse.

Now Your Eclipse is ready to use Git Repository Plugin.

You can also verify the Git installation.

Step 1.) Go to Help > Install New Software

Step 2.) Click on Already Installed and verify plugin is installed.

Else you can verify by searching on Windows => preference => type egit on search box.



Screenshot 1:-





Screenshot 2:-







Hope it will help you.





Follow for more details on Google+ and @Facebook!!!

Find More :-


Error occured during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

This issue I faced with window 8. When I was trying to execute java command from command prompt it was showing this error.After long time analysis I found the reason for this issue. This issue is really ambiguous.Its normally a path issue, if your class path has configured proper and still its not working then it might be a big reason to worry.

Solutions 1 :- Check your class path , if not set then use the below command to set.

path = your_java_installation_bin_path; 

Solutions 2 :- Probably there is few more java.exe file in your windows directory (i.e. C:\) .Normally when windows automatic updates works on your machine it may be install java into some other reference directory and it may be the cause.So, when you are trying to execute the java command from command prompt its not able to locate the exact path . As a solution , I have done this
by removing all the java.exe files from windows directory.

You can search the java.exe file from windows directory and remove all java application files , except your own java installation directory. After removing all those extra java application files its working fine for me. Below the screen shot for finding and removing the java application file.






Hope it will help you.


See Also

java.library.path setting in netbeans for .dll/.so files

This issue has wasted my 2 days of time. Setting java library class path on NetBean IDE is bit tricky.
Finally I found and its working now. Some little bit setting you have to do with your NetBean IDE.This setup is only for NetBean IDE.

Follow the Steps :-

==>Right click on the Project
==>Properties
==>Click on RUN
==>VM Options : -Djava.library.path="C:\Your Directory where Dll is present"
==>Ok

Its working 100%. I have done this in my own project settings.



Hope it will help you.

See Also