Wednesday, October 12, 2016

What is Volatile keyword in Java

The volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory because of this it's guaranteed that all reader thread will see updated value of the volatile variable once write operation completed.

So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in an int or a boolean variable then  you can declare them as volatile variable.

The Java volatile keyword cannot be used with method or class and it can only be used with a variable


Note: If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable

Singleton Pattern

Singelton pattern restricts the instantiation of a class and ensures that only one instance of the class exists per JVM.

To implement Singleton pattern, we have to follow the following step.

1. Constructor should be private.
2. Public static method that returns the instance of the class.

Lazy Initialization:

When you call the getInstance method then the object of the singleton class is created.

public class SingletonPattern {

private static SingletonPattern instance;

private SingletonPattern() {
}

public static SingletonPattern getInstance() {
if (instance == null) {
instance = new SingletonPattern();
}
return instance;
}
}

Thread-Safe Singleton:

In the case of thread safe singleton, we use the synchronized block or synchronized method to create the thread safe singleton class.
Below example is also known as double check locking. 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. 

public class ThreadSafeSingleton {

    private volatile ThreadSafeSingleton instance;
    
    private ThreadSafeSingleton(){}
    
    public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
        if(instance == null){
            synchronized (ThreadSafeSingleton.class) {
                if(instance == null){
                    instance = new ThreadSafeSingleton();
                }
            }
        }
        return instance;
    }
    
}


Bill Pugh Singleton Implementation:


In this approach when the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class get loaded and create the singleton class instance.


public class Logger {

    private Logger(){}
    
    private static class SingletonHelper{
        private static final Logger INSTANCE = new Logger();
    }
    
    public static Logger getInstance(){
        return SingletonHelper.INSTANCE;
    }
}


Note: Above approach doesn't require Synchronization.

Enum Singleton:

When we use the reflection then above all approach break and we are able  to create more than one object of each Singleton class to overcome this challenge we are using the enum singleton class.

public enum EnumSingleton {

     INSTANCE;  
}
Note:Only drawback of above approach is that it is not supporting the lazy loading.


Difference between Singleton Pattern vs Static Class in Java

If your class don't maintain any state then use static class over singleton.

If your requirement needs to maintain state then Singleton pattern is the better choice because in concurrent environment static class could lead subtle race condition.

In the case of a heavy object, we can lazily load the singleton class but static class alway eagerly loaded.

Static class provide better  performance than Singleton pattern because static methods are bonded on compile time.

java.lang.Math is an example of static class.
java.lang.Runtime is an example of Singleton class.