How to create a Singleton class
What is Singleton Class?
1. If a class has only one instance at one point of time, it is called singleton class
2. The name itself indicates (singleton - one)
3. Singleton is a simplest design pattern in java

How to make a class singleton
1. To make a class singleton we have to restrict the class object creation more than once then only it can be called as singleton class...
2. So to restrict object creation in sub classes we have to make the constructor private
3. Since we need to have single object across environment we have to
4. Use Private static variable to create instance of the class.
5. Now to make the created object accessible in sub Classes we have to provide a public static method (getInstance()) which returns the 
created object, instead of creating new object.
6. Singleton pattern is used for logging, drivers objects, caching and thread pool

There are different approaches of Singleton pattern implementation and design concerns with the implementation.

1.Eager initialization
2.Static block initialization
3.Lazy Initialization
4.Thread Safe Singleton
5.Enum Singleton

Eager initialization

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton classbut it has a drawback that instance is created even though client application might not be using it.
Here is the implementation of static initialization singleton class.

If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios,
Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method. Also this method doesn’t provide any options for exception handling.

Static block initialization

Static block initialization implementation is similar to eager initialization, except that instance of class 
is created in the static block that provides option for exception handling

 

Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create Singleton class that supports lazy initialization.

Lazy Initialization

Lazy initialization method to implement Singleton pattern creates the instance in the global access method.
Here is the sample code for creating Singleton class with this approach.

The above implementation works fine in-case of single threaded environment but when it comes to multi-threaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class. In next section, we will see different ways to create a thread-safesingleton class.

Thread Safe Singleton

The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. 
General implementation of this approach is like the below class.

Above implementation works fine and provides thread safety but it reduces the performance because of cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances .To avoid this extra overhead every time,double checked locking principle is used. In this approach,
the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created. Below code snippet provides the double checked locking implementation.

Enum Singleton

Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. 
Since Java Enum values are globally accessible, so is the singleton. 
The drawback is that the enum type is somewhat inflexible;
for example, it does not allow lazy initialization.


Programming Interview Questions for Freshers

Here i am posting few programming questions mostly asked in interview for freshers, but along with the solution if there is any scope for improvement in
programming i have given different ways to solve the same problem....

1.Count Vowels in the input String
vowels are “aeiou” other than vowels are consonents..so lets see the simple      program...Always separate your logic from main method, and call the method in main   method.
 



2. Check whether the given number is even or Odd


3. Check whether the given number is palindrome or not


4. Check whether the given number is prime number or not


5. Fibonacci series


6. Fibonacci series using recursion


Marker Interface in Java

Marker Interface is an interface with no method or field or in simple empty interface.The marker        interfaces are also called as tag interface
Eg: Serializable, Clonnable, Remote interface.
Another explanation for marker interface is:
“An interface is called a marker interface when it is provided as a handle by Java interpreter to  mark a class so that it can provide special behavior to it at run time and  they do not have any method declarations” 
If Marker interface doesn’t have any method or field what is the use of            implementing the marker interface?
When we carefully look into, we can see that, they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it,  similar way if JVM sees one class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM. Apart from using built in marker interface for making a class Serializable or Clonnable. One can also develop his own marker interface .Marker interface is a good way to classify code.

Transient Variable in Java

1. Transient is a keyword
2. User very less
3. Transient is used in serialization
4. Variable declared as transient can be avoided from being serialized
5. If we would like to exclude any property of an object from being serialized we mark it transient and then JVM doesn't serialize it.

Why do we need transient variable?
6. It provides some control over which variables you want to be serialized and which you want to exclude
7. It gives you flexibility to exclude some of object properties from serialization process

Which variable you should mark transient?
Since we know the purpose of transient keyword or having transient variable its make sense to think about which variable should be marked as transient, any variable whose value can be calculated from other variables doesn't require to be saved.
 For example if you have a field called "interest" whose value can be derived from other fields e.g. principle, rate, time etc then there is no need to serialize it.

Example
public class Stock {
    private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
    private String symbol; //will be serialized
    private BigInteger price; //serialized
    private long quantity; //serialized
}

Note:
1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.

2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to 
instruct "do not save this field" and static variables are not saved anyway during serialization.

3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of re-initializing a final variable during de-serialization
.
4) Transient variable in java is not persisted or saved when an object gets serialized.