Thursday, 4 October 2018

Singleton Design Pattern

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Application. The singleton class must provide a global access point to get the instance of the class.

Approach for Singleton:
  • Private constructor to restrict instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
Bellow are the different approaches of Singleton pattern implementation and design concerns with the implementation.

Eager initialization
Static block initialization
Lazy Initialization
Thread Safe Singleton
Bill Pugh Singleton Implementation
Using Reflection to destroy Singleton Pattern
Enum Singleton
Serialization and Singleton

----------------------------------------------------------------------------------------------------------
package com.test;

public class SingletonClone implements Cloneable {

@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}

----------------------------------------------------------------------------------------------------------
package com.test;

import java.io.Serializable;

public class JavaSingleton  extends SingletonClone implements Serializable{

/**
*/
private JavaSingleton() {
if (javaSingleton != null) {
throw new IllegalStateException("Inside JavaSingleton(): JavaSingleton " +
"instance already created.");
}
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
throw new CloneNotSupportedException();
}
private static JavaSingleton javaSingleton = null;


protected Object readResolve() 
return javaSingleton; 

public static JavaSingleton getInstance(){

if(javaSingleton==null){
synchronized (JavaSingleton.class) {
if(javaSingleton==null){
javaSingleton = new JavaSingleton();
System.out.println("object creation "+Thread.currentThread().getName()+javaSingleton);
}

}
}
return javaSingleton;
}

}
------------------------------------------------------------------------------------------------------------

package com.test;

public class TestMultiThreadingSingleton implements Runnable {

@Override
public void run() {

JavaSingleton javaSingleton = JavaSingleton.getInstance();
try {
JavaSingleton javaSingleton1 = (JavaSingleton) javaSingleton.clone();
System.out.println(Thread.currentThread().getName() + "-----" + javaSingleton +"--------------"+javaSingleton1);
} catch (Exception exception) {
// TODO: handle exception
exception.getMessage();
}

}

}
-----------------------------------------------------------------------------------------
package com.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class TestSingleton {
public static void main(String[] args) {
Thread thread = new Thread(new TestMultiThreadingSingleton(),"A");
Thread thread1 = new Thread(new TestMultiThreadingSingleton(),"B");
Thread thread2 = new Thread(new TestMultiThreadingSingleton(),"C");
Thread thread3 = new Thread(new TestMultiThreadingSingleton(),"D");
thread.start();
thread1.start();
thread2.start();
thread3.start();
EnumSingleton enumSingleton = EnumSingleton.INSTANCE;
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE;
System.out.println("desiarialize object -- enumSingleton"+enumSingleton);
System.out.println("desiarialize object -- enumSingleton1"+enumSingleton1);
try {
    /* Serializable-Deserializable
    JavaSingleton javaSingleton = JavaSingleton.getInstance();
ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream("C:\\Users\\CBEC14\\Desktop\\abc.tx"));
objectOutput.writeObject(javaSingleton);
System.out.println(javaSingleton);
objectOutput.close();
    
        ObjectInput input = new ObjectInputStream(new FileInputStream("C:\\Users\\CBEC14\\Desktop\\abc.tx"));     
        JavaSingleton javaSingleton2=(JavaSingleton)input.readObject();
        System.out.println("desiarialize object"+javaSingleton2);*/
// Reflection test
Constructor[] constructors = 
             JavaSingleton.class.getDeclaredConstructors();
     for (Constructor constructor : constructors) 
     {
         // Below code will destroy the singleton pattern
         constructor.setAccessible(true);
         JavaSingleton  instance2 = (JavaSingleton) constructor.newInstance();
         System.out.println("reflection object"+instance2);
         break;
     }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
---------------------------------------------------------------
package com.test;


public  enum EnumSingleton {
INSTANCE

}
---------------------------------------------------------------------------

Saturday, 15 April 2017

Javaforinterview: Serialization uses and example

Javaforinterview: Serialization uses and example: Serialization is the process of converting an object's and its references objects to a sequence of bytes, as well as the process of reb...

Serialization uses and example

Serialization is the process of converting an object's and its references objects to a sequence of bytes, as well as the process of rebuilding those bytes into  object .in simple words Converting an object to bytes and bytes back to object.
Serialization is used when you want to persist the object. It is also used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In general, serialization is used when we want the object to exist beyond the lifetime of the JVM.


Here are some uses of serialization
  • To persist data for future use.
  • To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
  • To "flatten" an object into array of bytes in memory.
  • To store user session in Web applications.
  • To send objects between the servers in a cluster

A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.ExternalizableDeserialization is the process of converting the serialized form of an object back into a copy of the object.




Example:

import java.io.Serializable;

public class Person implements Serializable {
        private String firstName;
        private String lastName;
        // stupid example for transient
        transient private Thread myThread;

        public Person(String firstName, String lastName) {
                this.firstName = firstName;
                this.lastName = lastName;
                this.myThread = new Thread();
        }

        public String getFirstName() {
                return firstName;
        }

        public void setFirstName(String firstName) {
                this.firstName = firstName;
        }

        public String getLastName() {
                return lastName;
        }

        public void setLastName(String lastName) {
                this.lastName = lastName;
        }

        @Override
        public String toString() {
                return "Person [firstName=" + firstName + ", lastName=" + lastName
                                + "]";
        }

}

The following code example show you how you can serializable and de-serializable this object.



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
        public static void main(String[] args) {
                String filename = "time.ser";
                Person p = new Person("Sam", "R");

                // save the object to file
                FileOutputStream fos = null;
                ObjectOutputStream out = null;
                try {
                        fos = new FileOutputStream(filename);
                        out = new ObjectOutputStream(fos);
                        out.writeObject(p);

                        out.close();
                } catch (Exception ex) {
                        ex.printStackTrace();
                }
                // read the object from file
                // save the object to file
                FileInputStream fis = null;
                ObjectInputStream in = null;
                try {
                        fis = new FileInputStream(filename);
                        in = new ObjectInputStream(fis);
                        p = (Person) in.readObject();
                        in.close();
                } catch (Exception ex) {
                        ex.printStackTrace();
                }
                System.out.println(p);
        }
}

Monday, 20 March 2017

Exception Handling

 Exception Handling with an example?


Exception Handling helps us to recover from an unexpected situations – File not found or network connection is down. The important part in exception handling is the try – catch block. Look at the example below. When exception is handled in a method, the calling methods will not need worry about that exception. Since Exception Handling is added in the method method2, the exception did not propogate to method1 i.e. method1 does not know about the exception in method2.

    public static void main(String[] args) {

        method1();

        System.out.println("Line after Exception - Main");

    }

 

    private static void method1() {

        method2();

        System.out.println("Line after Exception - Method 1");

    }

 

    private static void method2() {

        try {

            String str = null;

            str.toString();

            System.out.println("Line after Exception - Method 2");

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE

            System.out.println("Exception Handled - Method 2");

        }

    }

Program Output


Exception Handled - Method 2

Line after Exception - Method 1

Line after Exception - Main

Few important things to remember from this example.

·         If exception is handled, it does not propogate further.

·         In a try block, the lines after the line throwing the exception are not executed.

What is the use of finally block in Exception Handling?


When an exception happens, the code after the line throwing exception is not executed. If code for things like closing a connection is present in these lines of code, it is not executed. This leads to connection and other resource leaks.

Code written in finally block is executed even when there is an exception.

Consider the example below. This is code without a finally block . We have Connection class with open and close methods. An exception happens in the main method. The connection is not closed because there is no finally block.Connection that is opened is not closed. This results in a dangling (un-closed) connection.Finally block is used when code needs to be executed irrespective of whether an exception is thrown.

class Connection {

    void open() {

        System.out.println("Connection Opened");

    }

 

    void close() {

        System.out.println("Connection Closed");

    }

}

 

public class ExceptionHandlingExample1 {

 

    public static void main(String[] args) {

        try {

            Connection connection = new Connection();

            connection.open();

 

            // LOGIC

            String str = null;

            str.toString();

 

            connection.close();

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE

            System.out.println("Exception Handled - Main");

        }

    }

}

Output

Connection Opened

Exception Handled - Main

Let us now move connection.close(); into a finally block. Also connection declaration is moved out of the try block to make it visible in the finally block. Connection is closed even when exception is thrown. This is because connection.close() is called in the finally block. Finally block is always executed (even when an exception is thrown). So, if we want some code to be always executed we can move it to finally block.

    public static void main(String[] args) {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC

            String str = null;

            str.toString();

 

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE - BAD PRACTICE

            System.out.println("Exception Handled - Main");

        } finally {

            connection.close();

        }

    }

Output

Connection Opened

Exception Handled - Main

Connection Closed

In what kind of scenarios, a finally block is not executed?


Code in finally is NOT executed only in two situations.

·         If exception is thrown in finally.

·         If JVM Crashes in between (for example, System.exit()).

Is a finally block executed even when there is a return statement in the try block?


Yes. In the example below, connection.close() method is called even though there is a return in the catch block.

private static void method2() {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC    

            String str = null;

            str.toString();

            return;

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE - BAD PRACTICE

            System.out.println("Exception Handled - Method 2");

            return;

        } finally {

            connection.close();

        }

    }

Is a try block without corresponding catch block allowed?


Yes. try without a catch is allowed. Example below.

private static void method2() {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC

            String str = null;

            str.toString();

        } finally {

            connection.close();

        }

    }

However a try block without both catch and finally is NOT allowed until before Java 7. Below method would give a Compilation Error!! (End of try block).

    private static void method2() {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC

            String str = null;

            str.toString();

        }//COMPILER ERROR!!

    }

With Java 7, for try blocks doing automatic resource management - it is allowed not to have both catch and finally.

  try (FileInputStream input = new FileInputStream("file.txt")) {

   int data = input.read();

   while (data != -1) {

    System.out.print((char) data);

    data = input.read();

   }

  }

 

Explain the hierarchy of Exception related classes in Java?


Throwable is the highest level of Error Handling classes.

Below class definitions show the pre-defined exception hierarchy in Java.

//Pre-defined Java Classes

class Error extends Throwable{}

class Exception extends Throwable{}

class RuntimeException extends Exception{}

Below class definitions show creation of a programmer defined exception in Java.

//Programmer defined classes

class CheckedException1 extends Exception{}

class CheckedException2 extends CheckedException1{}

 

class UnCheckedException extends RuntimeException{}

class UnCheckedException2 extends UnCheckedException{}

What is difference between an Error and an Exception?


Error is used in situations when there is nothing a programmer can do about an error. Ex: StackOverflowError, OutOfMemoryError. Exception is used when a programmer can handle the exception.

What is the difference between a Checked Exception and an Un-Checked Exception?


RuntimeException and classes that extend RuntimeException are called unchecked exceptions. For Example: RuntimeException,UnCheckedException,UnCheckedException2 are unchecked or RunTime Exceptions. There are subclasses of RuntimeException (which means they are subclasses of Exception also.)

Other Exception Classes (which don’t fit the earlier definition). These are also called Checked Exceptions. Exception, CheckedException1,CheckedException2 are checked exceptions. They are subclasses of Exception which are not subclasses of RuntimeException.

How do you throw a Checked Exception from a Method?


Consider the example below. The method addAmounts throws a new Exception. However, it gives us a compilation error because Exception is a Checked Exception.

All classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown. Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the method should declare that it throws the exception

Example without throws: Does NOT compile


class AmountAdder {

    static Amount addAmounts(Amount amount1, Amount amount2) {

        if (!amount1.currency.equals(amount2.currency)) {

            throw new Exception("Currencies don't match");// COMPILER ERROR!                // Unhandled exception type Exception

        }

        return new Amount(amount1.currency, amount1.amount + amount2.amount);

    }

}

Example with throws definition


Let's look at how to declare throwing an exception from a method.

Look at the line "static Amount addAmounts(Amount amount1, Amount amount2) throws Exception". This is how we declare that a method throws Exception.

class AmountAdder {

    static Amount addAmounts(Amount amount1, Amount amount2) throws Exception {

        if (!amount1.currency.equals(amount2.currency)) {

            throw new Exception("Currencies don't match");

        }

        return new Amount(amount1.currency, amount1.amount + amount2.amount);

    }

}

How do you create a Custom Exception Classes?


We can create a custom exception by extending Exception class or RuntimeException class. If we extend Exception class, it will be a checked exception class. If we extend RuntimeException class, then we create an unchecked exception class.

Example


class CurrenciesDoNotMatchException extends Exception{

}

Let’s now create some sample code to use CurrenciesDoNotMatchException. Since it is a checked exception we need do two things a. throw new CurrenciesDoNotMatchException(); b. throws CurrenciesDoNotMatchException (in method declaration).

class AmountAdder {

    static Amount addAmounts(Amount amount1, Amount amount2)

            throws CurrenciesDoNotMatchException {

        if (!amount1.currency.equals(amount2.currency)) {

            throw new CurrenciesDoNotMatchException();

        }

        return new Amount(amount1.currency, amount1.amount + amount2.amount);

    }

}

How should the Exception catch blocks be ordered ?


Specific Exception catch blocks should be before the catch block for a Generic Exception. For example, CurrenciesDoNotMatchException should be before Exception. Below code gives a compilation error.

    public static void main(String[] args) {

        try {

            AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("DOLLAR",

                    5));

        } catch (Exception e) { // COMPILER ERROR!!

            System.out.println("Handled Exception");

        } catch (CurrenciesDoNotMatchException e) {

            System.out.println("Handled CurrenciesDoNotMatchException");

        }

    }

What are the new features related to Exception Handling introduced in Java7?


Automatic resource management. JVM takes care of closing the connection when we use try with resources.

  try (FileInputStream input = new FileInputStream("file.txt")) {

   int data = input.read();

   while (data != -1) {

    System.out.print((char) data);

    data = input.read();

   }

  }

 

Multiple Repeated Exception Blocks not needed anymore. We can use a single exception block to catch multiple exception types.

catch (IOException|SQLException ex) {

    logger.log(ex);

    throw ex;

}

Can you explain some Exception Handling Best Practices?


Never Completely Hide Exceptions. At the least log them. printStactTrace method prints the entire stack trace when an exception occurs. If you handle an exception, it is always a good practice to log the trace.


     public static void main(String[] args) {

        try {

            AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE",

                    5));

            String string = null;

            string.toString();

        } catch (CurrenciesDoNotMatchException e) {

            System.out.println("Handled CurrenciesDoNotMatchException");

            e.printStackTrace();

        }

    }


Best practices you follow while doing Exception handling in Java ?




There are lot of best practices, which can help to make your code robust and flexible at same time, here are few of

them:




1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since

NullPointerException is most infamous of all Java exceptions, there are lot of techniques andcoding best practices to minimize NullPointerException. You can check that link for some specific examples.




2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in Exception handling because they just

ate Exception without any clue, at bare minimum print stack trace but you should do alternative operation which make sense or defined by requirements.




3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it

improves readability of code by removing boiler plate exception handling code




4) Never let your database Exception flowing till client error. since most of application deal

with database and SQLException is a checked Exception in Java you should consider handling any database related

errors in DAO layer of your application and only returning alternative value or

something meaningfulRuntimeException which client can understand and take action.




5) calling close() methods for connections, statements, and streams on finally block in

Java.

Sunday, 19 March 2017

OOPS Benefits

It simplifies the software development and maintenance by providing some concepts:
  • Object.
  • Class.
  • Inheritance.
  • Polymorphism.
  • Abstraction.
  • Encapsulation.

Benefits of the Java Collections Framework

 OOP offers several benefits to the program designer and the user. Object-orientation contributes to the solutions of many problem associated with the development and quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. The principal advantages are:

·        Through inheritance, we can eliminate redundant code and extend the use of existing classes.
·        We can built programs from standard working modules that communicate with one another rather than, having to start writing the code from scratch. This leads to saving of development time and higher productivity.
·        The principle of data hiding helps the programmers to built secure program that can’t be invaded by code in other parts of the program.
·        It is possible to have multiple objects to coexist without any interference.
·        It is possible to map objects in the problem domain to those objects in the program.
·        It is easy to partition the work in a project based on objects.
·        The data-centered design approach enables us to capture more details of the model in an implementable form.
·        Object-oriented systems can be easily upgraded from small to large system
·        Message passing technique for communication between objects make the interface descriptions with external system much simpler.
·        Software complexity can be easily managed.