32

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();
        System.out.println(singleton1);

        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton2);

        Constructor<Singleton> c = Singleton.class
                .getDeclaredConstructor((Class<?>[]) null);
        c.setAccessible(true);
        System.out.println(c);

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

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

}

How to resolve this?

Thank you

20
  • 7
    The best way, in 99.99% of cases, based on my years of professional experience, is to not do it. What do you think you need a Singleton for, really? Commented Dec 6, 2010 at 3:27
  • 4
    Firstly, singletons are evil. Secondly, singletons are global variables, Thirdly, don't use singletons. Also, you cannot stop reflection from being able to bad things to your class. DO NOT TRY! Commented Dec 6, 2010 at 3:29
  • 1
    I think I'll take your advice, if somebody uses reflection to mess up.. it is their problem.. not mine. Commented Dec 6, 2010 at 3:37
  • 4
    @Arun, I'd create the object once and pass it to the constructor of all the objects that need the settings. Commented Dec 6, 2010 at 4:31
  • 3
    guys, the question asked is to resolve the issue, not to go Dr. House about if singeltons are good or bad. Commented Nov 4, 2013 at 21:03

7 Answers 7

17

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.

E.g.

public class Config {

    private static final Properties PROPERTIES = new Properties();

    static {
        try {
            PROPERTIES.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Loading config file failed.", e);
        }
    }

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

    // ...
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your suggestion. I would try to implement this.
If you're new to static initializers, you may find this answer useful as well.
This is still a singleton. It's just a singleton that is not lazy loaded. WTH is going on here... ??
@Rob: This is not a capital-S Singleton, though. (1) The single instance is of a different type, and (2) it's never directly exposed -- only its behavior is. It's still pretty ugly IMO, but it at least doesn't pretend to be a discrete object when it's not.
@nikel: because it's not optional.
|
5

I will implement singleton in below way.

From Singleton_pattern described by wikiepdia by using Initialization-on-demand holder idiom

This solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized

public final class  LazySingleton {
    private LazySingleton() {}
    public static LazySingleton getInstance() {
        return LazyHolder.INSTANCE;
    }
    private static class LazyHolder {
        private static final LazySingleton INSTANCE = new LazySingleton();
    }
    private Object readResolve()  {
        return LazyHolder.INSTANCE;
    }
}

1 Comment

In my case the public final was what I was missing from the main class declaration.
4

If you are using reflection to pierce encapsulation, you should not be surprised when behavior of your class is altered in incorrect ways. Private members are supposed to be private to the class. By using reflection to access them you are intentionally breaking the behavior of the class, and the resultant "duplicate singleton" is expected.

In short: Don't do that.

Also, you might consider creating the singleton instance in a static constructor. Static constructors are synchronized and will only run once. Your current class contains a race condition -- if two separate threads call getInstance() when it has not been previously called, there is a possibility that two instances will be created, one of them being exclusive to one of the threads, and the other becoming the instance that future getInstance() calls will return.

Comments

0

Best way to create Singleton Class in java is using Enums.

Example as below :

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; 

enum SingleInstance{
    INSTANCE;

    private SingleInstance() {
        System.out.println("constructor");
    }   
}

public class EnumSingletonDemo {

    public static void main (String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        SingleInstance s=SingleInstance.INSTANCE;
        SingleInstance s1=SingleInstance.INSTANCE;

        System.out.println(s.hashCode() + " "+s1.hashCode());//prints same hashcode indicates only one instance created

    //------- Serialization -------
    ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("sample.ser"));
    oos.writeObject(s);
    oos.close();

    //------- De-Serialization -------
    ObjectInputStream ois=new ObjectInputStream(new FileInputStream("sample.ser"));
    SingleInstance s2=(SingleInstance) ois.readObject();

    System.out.println("Serialization :: "+s.hashCode()+" "+s2.hashCode());// prints same hashcodes because JVM handles serialization in case of enum(we dont need to override readResolve() method)

   //-----Accessing private enum constructor using Reflection-----

    Class c=Class.forName("SingleInstance");

    Constructor co=c.getDeclaredConstructor();//throws NoSuchMethodException
    co.setAccessible(true);
    SingleInstance newInst=(SingleInstance) co.newInstance();           

}
}

NoSuchMethodException is thrown because we can't create another instance of enum 'SingleInstance' through its private constructor using Reflection.

In Case of Serialization enum implements serializable interface by default.

Comments

-1

I think you can check whether an instance already exists in the constructor and if exists throw an exception

if(me != null){
    throw new InstanceAlreadyExistsException();
}

1 Comment

There is no need to do this in a private member, since private members should not be accessed outside the class. If someone wants to use reflection to access private members, the resultant behavior is their problem.
-1
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {


    private static DBConnection dbConnection;
    private Connection connection;

    private DBConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(/*crate connection*/);
    }

    public Connection getConnection(){
        return connection;
    }
    public static DBConnection getInstance() throws SQLException, ClassNotFoundException {
        return (null==dbConnection) ? (dbConnection = new DBConnection()) : dbConnection;
    }
}

 

1 Comment

Can you please add an explanation to your answer? Why does using the code you provided work and what is the problem?
-2

just follow the singleton pattern class diagram,

SingletonClass - singletonObject: SingletonClass - SingletonClass() + getObject(): SingletonClass

Key point,

  • private your constructor
  • the instance of your class should be inside the class
  • provide the function to return your instance

Some code,

public class SingletonClass {
    private static boolean hasObject = false;
    private static SingletonClass singletonObject = null;

    public static SingletonClass getObject() {
        if (hasObject) {
            return singletonObject;
        } else {
            hasObject = true;
            singletonObject = new SingletonClass();
            return singletonObject;
        }
    }

    private SingletonClass() {
        // Initialize your object.
    }
}

1 Comment

This code is inherently not thread-safe. If two threads are in getObject() at exactly the same time, two instances can be created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.