Multiple instances of Singleton class. Possible?
Asked Answered
C

7

6

I found this explanatory link which states

Ensure a class has one instance, and provide a global point of access to it.

I recently appeared at an interview and to my surprise it was asked from me too that can singleton class have multiples instances, my technology being Java and Objective C. My answer to this question was NO which I believe is right as Singleton variable being global shall check if it is null or not. And it will be null only the first time.
However out of curiosity I was confirming it. Can someone provide a confirmation with explanation weather I am right or wrong.

Canonical answered 27/11, 2014 at 5:41 Comment(3)
This thread might be helpful: #3065161Daughter
geeksforgeeks.org/…Doble
Sounds like you need multition.Fetishist
P
16

The word Singleton by definition(of Design Patterns) does not allows multiple instances, but yeah you can tweak the class to create multiple instances but then it won't be considered as a Singleton by definition

Predatory answered 27/11, 2014 at 5:56 Comment(0)
D
6

Well-designed singleton can have only one instance per application. Creating of multiple instances is a mistake in the application design. It might happen in some cases, e.g.:

  • Non thread safe singleton with lazy initialization: several threads are trying to get an instance and creates multiple instances. Good practice for lazy singleton is init on demand
  • When using DI containers for managing singletons (Spring for example) and several contexts every context will create his own instance of class.
Dg answered 27/11, 2014 at 5:57 Comment(0)
C
4

Can singleton class have multiple instances?

Ans: NO

This is the simple example for Singleton class in java. By calling Singleton.getInstance() you can get the instance of this Singleton class. Here instance is private static and constructor is private so only one object is available per JVM.

 public class Singleton {    

        private static Singleton instance = new Singleton ();

        private Singleton () {
        }

        public static Singleton getInstance() {
            return instance;
        }
    }

Lazy instantiation to create the singleton also known as classic singleton and it is not a thread safe version

public class Singleton {    

            private static Singleton instance = null;

            private Singleton () {
            }

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

A thread safe lazy initialization singleton class can be implemented in a simple way as follows

public class Singleton {
    private Singleton() {}

    private static class LazyHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return LazyHolder.INSTANCE;
    }
}
Coronagraph answered 27/11, 2014 at 6:15 Comment(1)
The lazy version is not thread safe. It's possible to get multiple instances if multiple threads access getInstance(). I suspect the interviewer was digging for thread awareness. See https://mcmap.net/q/271885/-thread-safe-singleton-classClactonian
O
3

I'm styding for the Architect certification and this question came up.

I believe this is better answered when you go to the source, which I believe to be the book [Design Patterns: Elements of Reusable Object-Oriented Software] by Erich Gamma / Richard Helm / Ralph Johnson / John Vlissides. I did a quick research and didn't find this defined earlier than the book release.

Although at the beginning (page 127) it states that the intent is to "Ensure a class only has one instance, and provide a global point of access to it.", on the section 'Consequences', bullet 4, it has the variation "Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change."

With that said, I believe that the formal answer is that the singleton CAN have multiple instances, although I particularly don't see this being applied in the real world (by the way whoever put this in your interview doesn't seem really interested in assessing your useful skills).

Oro answered 27/11, 2018 at 11:35 Comment(0)
S
2

I know it is an old one but I hope I'll help others out.

Sadly the Singleton pattern has got many definitions. Examples:

Definition 1 HTDIN:

Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.

Definition 2 Wikipedia:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

The first one is more strict but if you look at the second description is states that there could be multiple instances. This way you are able to do something like pooling.

final class Singleton {
    private static int ROUND_ROBIN_COUNTER = Integer.MAX_VALUE;
    private static final List<Singleton> INSTANCES = Arrays.asList(new Singleton(), new Singleton(), new Singleton());

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCES.get(Math.abs((ROUND_ROBIN_COUNTER++)%INSTANCES.size()));
    }
}

According to the first definition this is not a singleton, but the second one allows that. I am reading the OCM Java EE 6 Enterprise Architect Exam Guide it also agrees with the Wikipedia definition.

Switzerland answered 30/1, 2018 at 16:46 Comment(3)
Is there a better term to use for " restrict the instantiation to a certain number of objects" than singleton?Graphite
I would say pooling is a better and more correct term for that case (or at least more understood by people).Switzerland
I see where pooling comes from, such as having a limited number of connections to one database. Nonetheless, a sample use-case that makes the case for calling many instances of a class to be singleton, is specializations. Say there are 2 databases: DB("foo") and DB("bar"). Each should be created only once in the process, but they are both DB.Graphite
M
1

It's a good theoretical question, but the definition states very clearly that the pattern 'Ensure a class only has one instance'. You can build an almost identical pattern which allows you to instantiate maximum, let's say, 4 objects of the same type.

In that case, the definition of the pattern would have to be 'Ensure a class only a limited number of instances'.

You can look at the problem form a different angle. You would have to hold those 4 objects in a data structure. Either as hardcoded separate members(instance1, instance2,...) or in a list. In the second case, the list could be considered the singleton.

Monomial answered 1/12, 2018 at 21:12 Comment(0)
F
1

Well, this is a good question.

Initially, I can say NO if you don't use multiple distributing applications ( i.e. load balancer with multiple instances ), YES, if you use multiple distributing applications.

I have been working on this area for 3 months to create a service that must have only one instance when the application is live.

  • If you apply the singleton design pattern without using the Lazy holder, then the service can have multiple instances if it is being accessed by parallel threads.
  • If you use the lazy holder,

ex:

private static readonly Lazy<YourServiceName> s_instance = new(() => new YourServiceName());

then only one instance will be initialized even if it is being accessed by parallel threads.

However, this will work fine if you publish the application to one host, but it won't work if you have multiple hosts ( i.e you have a load balancer and multiple instances used ), because each host will have a separate copy of the application, and in this case YES, you will have multiple instances of singleton in multiple distributed application.

Farnesol answered 9/6, 2023 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.