Thursday, May 2, 2013

What is Singleton class in java with example? How to create Singleton class?



Singleton class is a class which has only one instance in whole JVM.
Example of singleton class in jdk is java.lang.Runtime,  getRuntime() method is used to create instance.

There are following ways to create Singleton class

What is Early and Lazy loading of Singleton and how will you implement it?
Early Loading: Singleton instance is created when class is loaded into memory.
Lazy Loading: Singleton instance is not created when class is loaded into memory.  When we call its getInstance() method only then its instance is created.  Such kind of phenomena is called lazy loading.
e.g Early Loading
public class Singleton {
                public static final Singleton INSTANCE = new Singleton ();
                private Singleton (){
                }
}

Lazy Loading
public class Singleton {
                private static final Singleton INSTANCE = new Singleton ();
                private Singleton (){        }
                public Singleton getInstance(){
                                return INSTANCE;
                }
}

Double checked locking in Singleton
public static Singleton getInstance(){
     if(null == INSTANCE){
         synchronized(Singleton.class){
         //double checked locking - because second check of Singleton instance with lock
                if(null == INSTANCE){
                    INSTANCE = new Singleton();
                }
            }
         }
     return INSTANCE;
}
Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.

In Java 1.5, there is an approach to implementing singletons. Simply make an enum type with one element:
Singleton using Enum in Java
// Enum singleton - This is the preferred approach
public enum Elvis {
                INSTANCE;
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Thursday, April 25, 2013

Get java sql connection from hibernate session

Get java sql connection from org hibernate Session

Hi we can get java sql connection object from org hibernate session object.
As i write a function getJavaSqlConnectionFromHibernateSession, which take session as an argument and return connection object.

private Connection getJavaSqlConnectionFromHibernateSession(Session session){
    SessionFactoryImplementor sessionFactoryImplementor = null;
    ConnectionProvider connectionProvider = null;
    java.sql.Connection connection = null ;
    try {
        sessionFactoryImplementor = (SessionFactoryImplementor)session.getSessionFactory();
        connectionProvider = (ConnectionProvider)sessionFactoryImplementor.getConnectionProvider().getConnection();
        connection = connectionProvider.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}
----------------------------------------------------------
Even we can use such kind of stuff.

private void doDBWork(){
    session.doWork(
            new Work() {
                public void execute(Connection connection) throws SQLException
                {
                     // here you get the java sql connection object and do any DB Work with it
                }
            }
        );
    session.disconnect();
}


Above stuff is suggested by JBoss. For more info you can visit Hibernate Session API docs at following url
http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html



Tuesday, April 23, 2013

Call private method of a class in java

Hi All,

We can execute/call/invoke private method of a Class with the help of Reflection and Mockit.
I give an example in which i have one class Student and that class having one private method showStudentDetails.
I have one another class StudentHack in which i execute that private method in two different methods.

Let us have a Student class
package com.om.demo;

public class Student {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
   
    private void showStudentDetails(){
        System.out.println("Student Name : "+name);
    }
}

Let us have another class StudentHack which Hack Student class

package com.om.demo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import mockit.Deencapsulation;

public class StudentHack {

    // Object of Student class
    private Student student = null;
    // Name of the private method
    private String methodName = "showStudentDetails";

    {
        student = new Student();
        student.setName("Ram");
    }

    public static void main(String[] args) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            NoSuchMethodException, SecurityException {

        StudentHack studentHack = new StudentHack();
        studentHack.callPrivateMethodWithReflection();
        studentHack.callPrivateMethodWithMockit();
    }

    public void callPrivateMethodWithReflection()
            throws IllegalArgumentException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException, SecurityException {
        // Name of the class
        Class c = Student.class;
        // Create method instance
        Method method = c.getDeclaredMethod(methodName);
        // Allow to access private method
        method.setAccessible(true);
        // call private method
        method.invoke(student, new Object[] {});
    }

    public void callPrivateMethodWithMockit() {
        Deencapsulation.invoke(student, "showStudentDetails");
    }
}


As shown above we can execute private method of a class with the help of Reflection and Mockit

Call private method with Reflection
    Step 1.    Create instance of java.lang.reflect.Method i.e. Method method = c.getDeclaredMethod(methodName);
            where methodName is an argument, which we want to call
    Step 2.    Allow to access private method i.e. method.setAccessible(true);
    Step 3.    Invoke private method i.e. method.invoke(student, new Object[] {});
            Here new Object[] {} is the array of objects which represents argument of method.
            If method contains argument then we need to pass arguments here.

Call private method with Mockit
    Step 1. Deencapsulation.invoke(student, "showStudentDetails");
            If method contains argument then we pass array of Object as 3rd argument.
            i.e. Deencapsulation.invoke(student, "showStudentDetails", new Object[] {});

Wednesday, April 17, 2013

Execute Log4j Logger statements in JUNIT to increase the code coverage

Execute Log4j Logger statements in JUNIT to increase the code coverage

Let us have a Student class

class Student{

    private static final Logger LOGGER = Logger
            .getLogger(Student.class);
    public void showStudent(){
        LOGGER.debug("Enter in showStudent method");
        /*
            Method Body
        */
        LOGGER.debug("Exit from showStudent method");
    }
}

Let us have another Test class StudentTest, which test the functionality of Student class

class StudentTest extends TestCase {

    private static final Logger LOGGER = Logger
            .getLogger(Student.class);
    Student student;       
    @Before
    public void setUp() throws Exception {
        student = new Student();
        LOGGER.setLevel(Level.DEBUG);
    }
   
    @Test
    public void testShowStudent(){
        student.showStudent();
    }
}

In this class we create a Logger object, and pass Student.class as an argument.
    private static final Logger LOGGER = Logger
            .getLogger(Student.class);

           
and set loglevel in setUp() method
    LOGGER.setLevel(Level.DEBUG);
   
Now when we execute student.showStudent() method in our test case then its logger statements also executes because we create an instance of Logger object and set its level to debug (i.e. Level.DEBUG)