Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Singleton class instances in a Web based Application

Tags:

java

singleton

I have this Singleton class inside a Web Application .

public class MyDAO 
 {


    private static MyDAO instance;

    private MyDAO() {
    }

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

I will access it this way

public void get_Data()
{

        MyDAO dao = MyDAO.getInstance();
}

How many Objects of MyDAO class will be created if there are 3 Users accessing the Application ??

Will there be one instance of MyDAO per User ??

like image 728
Pawan Avatar asked Sep 22 '12 15:09

Pawan


1 Answers

You must synchronize the access to the getInstance(). Otherwise some threads might see a not fully initialized version.

More on the Singleton Pattern

Once you synchronize it there will only be one instance in the JVM. No matter how many variables references to the object. But if you are running N servers there will be one instance in each JVM. So N instances in total.

You can double check if you are using Java 5.0 or older:

private static volatile MyDAO();
 public synchronized static MyDAO getInstance() {
    if (instance == null) {
        instance = new MyDAO();
    }
    return instance;

But if your application always needs an instance you can eagerly instantiate it:

private static MyDAO = new MyDAO();

But I would go for the Bill Purge solution:

    private static class MyDAOHolder { 
            public static final MyDAO INSTANCE = new MyDAO();
    }

    public static MyDAO getInstance() {
            return MyDAOHolder.INSTANCE;
    }
like image 87
ssedano Avatar answered Oct 25 '22 18:10

ssedano