Friday, December 14, 2018

Singleton Pattern

Singleton pattern is the simplest pattern in java and is under the creational pattern. some key points to use in singleton pattern.
  • It is static in nature
  • private constructor
  • private static instance of the class
  • public static getter method
  • no parameters to the constructor
create singleton class
public class Singleton {

    private static Singleton object = null;

    private Singleton() {
    }
    public static Singleton getInstance() {
        if (object == null) {
            object = new Singleton();
        }
        return object;
    }
    public void showMessage() {
        System.out.println("Singleton Pattern");
    }
}
create demo class
public class Demo {
    public static void main(String[] args) {
        Singleton object = Singleton.getInstance();
        object.showMessage();
    }
}
but this classic implementation not thread safe. therefore using synchronized make sure that the one thread can execute the getInstance();at one time.
As this;
public class Singleton {

    private static Singleton object = null;

    private Singleton() {
    }
    public static synchronized Singleton getInstance() {
        if (object == null) {
            object = new Singleton();
        }
        return object;
    }

}

What is the difference between JVM, JDK, JRE

JVM is abbreviated as Java Virtual Machine , JVM is the main component of java architecture. JVM is written in C programming language. Java compiler produce the byte code for JVM. JVM reading the byte code verifying the byte code and linking the code with the ibrary.

JRE is abbreviated as Java Runtime Environment. it is provide environment at runtime. It is physically exist. It contain JVM + set of libraries(jar) +other files.

JDK is abbreviated as Java Development Kit . it is develop java applications. And also Debugging and monitoring java applications . JDK contain JRE +development tools(javac,java)

Singleton Pattern

Singleton pattern is the simplest pattern in java and is under the creational pattern. some key points to use in singleton pattern. It is...