I have this singleton I'm trying to use, but getInstance can apparently return null:
class Singleton {
public static final String K_LEVEL = "level";
static Singleton instance = new Singleton();
private int level;
static Singleton getInstance() {
return instance;
}
int getLevel() {
return level;
}
void incrementLevel() {
System.out.println("LEVEL INCREASED TO " + ++level);
}
void addToLevel(int x) {
for(int i=0;i<x;i++)
incrementLevel();
}
}
class A {
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
Integer i = Integer.getInteger(Singleton.K_LEVEL);
s.addToLevel(i);
}
}
I heard implementing singletons in Java is very hard and prone to race conditions. Is my singleton pattern implemented wrong? I recently changed my code to look like this, and now getInstance returns null sometimes. Why?
$ java A -Dlevel=1
Exception in thread "main" java.lang.NullPointerException
at A.main(A.java:29)
System.out.println(i);
right befores.addToLevel(i);
print? – Ceasefire