Wednesday 24 October 2018

Singleton Design Pattern in Java


  • singleton is a way to restrict only one object per a class  

    There are multiple ways of creating a singleton object 

 1) eager initialized singleton 

      public class MySingelton1 {

private final static  MySingelton1 myobj =new MySingelton1();
private MySingelton1() {
System.out.println("new instance created MySingelton1");
}

public static MySingelton1 getMyobj() {
return myobj;
}
}

This class object is created  only once during the loading time itself 

2) lazy initialized singleton
  
   public class MySingelton2 {
private  static volatile MySingelton2 myobj=null;
private MySingelton2() {
System.out.println("new instance created MySingelton2");
}

public static MySingelton2 getMyobj() {
 if (myobj == null) {
synchronized (MySingelton2.class)
{
if (myobj == null) {
myobj = new MySingelton2();
}
}
}

return myobj;
}
}
 This class object is cretaed only once when you called the getMyobj() method for the first time.


Convert from List to IN params for SQL



         Convert from List to IN params for SQL 


public static <T> String getWithINParam(List<T> paraList) {
try {
if (null != paraList)
return paraList.stream().map(s -> new                                                                                                      StringBuilder("'").append(s).append("'")).collect(joining(","));                                               
} catch (Exception e) {
LOG.error("Error in setting IN para for SQL  ", e);

}
return "''";
}