How to Create Singleton Class in Java


In this example we will show how to use Private Constructor to develop singleton class in Java.

Source Code

package com.beginner.examples;

public class StaticInnerSingletonExample {
	 
    public static void main(String[] args){
    	// get singleton instance
        Singleton s = Singleton.getInstance();
        s.test();
    }
}
class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
    	// Double-Check
        if (singleton == null) {        	
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
    
    public void test(){
        System.out.println("It is a singleton example.");
    }
}

Output:

It is a singleton example.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments