How do you implement a singleton in Java, and what problems does the pattern create?
A singleton is a class with exactly one instance. You ask the class for the instance and it always gives you the same one.
public class Main {
public static void main(String[] args) {
Config a = Config.getInstance();
Config b = Config.getInstance();
System.out.println(a == b); // true, they are the same object
}
}
And here is the implementation with the thread safe version, which is the one you should use.
public class Config {
private static final Config INSTANCE = new Config();
private final java.util.Map<String, String> values = new java.util.HashMap<>();
private Config() {
values.put("mode", "live");
}
public static Config getInstance() {
return INSTANCE;
}
public String get(String key) {
return values.get(key);
}
}
And what problems does the pattern create? Five, and they are all real.
the problem why it hurts
----------------------------------- --------------------------------------------
it is hard to test the one instance is shared between
the tests
the state is hidden you cannot see that the class has
state from the constructor
the dependency is hidden the class reaches out for the
singleton instead of being given
it
it is not thread safe by default two threads can make two instances
it makes the code harder to the reader has to know that a
understand singleton exists
And the testing one is the worst of them. So a test changes the configuration and the next test sees the change, and the tests pass on their own and fail together. And you cannot give the class a different configuration because there is only one.
// The test problem. The state leaks between the tests.
@Test
void usesTheTestMode() {
Config.getInstance().set("mode", "test");
// This test now depends on the test above it.
}
@Test
void startsInLiveMode() {
// This fails if the test above ran first.
assertEquals("live", Config.getInstance().get("mode"));
}
And the thread safety one is worth knowing about, because the lazy version that everybody writes first has a bug in it.
// This is not thread safe. Two threads can both make one.
public static Config getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
Two threads can both see that the instance is null and both make one. So the class that was supposed to have exactly one instance has two. The fix is the version at the top of this answer, where the instance is made when the class is loaded.
So the rule to remember is this. The singleton gives you one instance and it takes away the ability to have two, and that is a big thing to give up.
The last question in this topic is about what teams use instead.