Arun P Johny Arun P Johny - 4 months ago 21
Java Question

How to create a singleton class

What is the best/correct way to create a singleton class in java?

One of the implementation I found is using a private constructor and a getInstance() method.

package singleton;

public class Singleton {

private static Singleton me;

private Singleton() {

public static Singleton getInstance() {
if (me == null) {
me = new Singleton();

return me;

But is implementation fails in the following test case

package singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {

* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws IllegalArgumentException
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException,
InvocationTargetException {
Singleton singleton1 = Singleton.getInstance();

Singleton singleton2 = Singleton.getInstance();

Constructor<Singleton> c = Singleton.class
.getDeclaredConstructor((Class<?>[]) null);

Singleton singleton3 = c.newInstance((Object[]) null);

if(singleton1 == singleton2){
System.out.println("Variable 1 and 2 referes same instance");
System.out.println("Variable 1 and 2 referes different instances");
if(singleton1 == singleton3){
System.out.println("Variable 1 and 3 referes same instance");
System.out.println("Variable 1 and 3 referes different instances");


How to resolve this?

Thank you


As per the comment on your question:

I've a properties file containing some keys value pairs, which is need across the application, that is why I was thinking about a singleton class. This class will load the properties from a file and keep it and you can use it from anywhere in the application

Don't use a singleton. You apparently don't need one-time lazy initialization (that's where a singleton is all about). You want one-time direct initialization. Just make it static and load it in a static initializer.


public class Config {

    private static final Properties PROPERTIES = new Properties();

    static {
        try {
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Loading config file failed.", e);

    public static String getProperty(String key) {
        return PROPERTIES.getProperty(key);

    // ...