8

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 ??

1
  • If multiples threads enter that if condition then it will be instantiated multiple times. It's not threadsafe. Commented Sep 22, 2012 at 15:39

3 Answers 3

5

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;
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Even for Load balancer which is of Sticky type do we need this Synchronized block ?? please specify .
Synchronized method could be overkill, since you need to synchronize only on creation
Are you talking about 3 users accessing or 3 java backend running?
3 Users accessing the Application which is deployed on 3 Web Servers as part of clustering process
2

No, it's one per JVM. Be careful about thread safety.

I'd read "Effective Java" and follow the recommendations for how to write a singleton properly. Yours isn't it.

Comments

0

There will only be one, that is the definition of a singleton.

To synchronize the instantiation, to make sure you only return a complete object you want to use:

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

Comments

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.