tomr345
tomr345

Reputation: 1

ConcurrentHashMap of Singleton Instances

I saw an answer on quora (https://www.quora.com/Can-we-create-mulitple-instances-of-singleton-classes-in-Java-if-so-how-if-not-then-why) that suggested creating a ConcurrentHashMap of Singleton instances 'keyed by an identifying string', but I'm unsure of how this would work. Here is my attempt:

public class SingletonClass {

static ConcurrentHashMap<String, SingletonClass> list = new ConcurrentHashMap<String, SingletonClass>();

private static SingletonClass instance = null;

static String name;

public SingletonClass() {
    this.name = "";
}

public SingletonClass(String name) {
    this.name = name;
}

public SingletonClass getInstance(String key) {
    SingletonClass result = list.get(key);
    if(result == null) {
        instance = new SingletonClass(name);
        list.putIfAbsent(key, instance);
        result = instance;
    }
    return result;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

And I have no idea how to proceed or how to create an instance of this and store a key,value pair in the list, and then retrieve the value again depending on the specific key? Any help would be much appreciated.

Upvotes: 0

Views: 1484

Answers (1)

Shadov
Shadov

Reputation: 5591

  • you are creating multiple instances, how is that a singleton then? It's not
  • getInstance() should be static in any case
  • you are using a static variable in your getInstance() method for no reason, you open this code to a racing condition this way (well, multiple racing conditions). And this variable is unnecessary, do everything in scope of this method
  • this is not a singleton pattern, this is an object pool of flyweight objects - same as wrapper classes (Integer, Long etc.) in Java

The point is that, with this approach, there will be no 2 objects with the same key.

// with your approach
SingletonClass one = SingletonClass.getInstance("someKey");
SingletonClass two = SingletonClass.getInstance("someKey");

System.out.println(one == two); // true, same object

// without your approach
SingletonClass three = new SingletonClass("someKey");
SingletonClass four = new SingletonClass("someKey");

System.out.println(three == four); // false, different objects

Saving memory, possibly time on object creation and possibly time on gc cycles.

Upvotes: 2

Related Questions