The following example defines 2 static variables. Variable 1 (myBoolean1) is defined above the MySingletonExample (instance) variable.
Variable 2 (myBoolean2) is defined below the MySingletonExample (instance) variable.
Both variables are set to true but only 1 variable (myBoolean1) shows the proper value when displayed.
public class MySingletonExample
{
//static volatile boolean myBoolean1 = false;
static boolean myBoolean1 = false;
private static volatile MySingletonExample instance = new MySingletonExample();
//static volatile boolean myBoolean2 = false;
static boolean myBoolean2 = false;
private MySingletonExample()
{
myBoolean1 = true;
myBoolean2 = true;
}
protected static MySingletonExample getInstance()
{
System.out.println("myBoolean1 = " + myBoolean1);
System.out.println("myBoolean2 = " + myBoolean2);
return instance;
}
public static void main(String[] args)
{
MySingletonExample.getInstance();
System.out.println("---------------------------");
MySingletonExample.getInstance();
}
}
When executed, this is the output.
myBoolean1 = true
myBoolean2 = false
myBoolean1 = true
myBoolean2 = false
Why doesn't myBoolean2 return true instead of false like myBoolean1?
The only different is the placement. Is there a "rule" when working with static variables?
myBoolean2
is set back to false after being set to true in the constructor, due to the order of static variable initialization.
Is there a "rule" when working with static variables?
Yes. A static singleton doesn't need static state. Just make them regular fields.
private static volatile MySingletonExample instance = new MySingletonExample();
private final boolean myBoolean1;
private final boolean myBoolean2;
private MySingletonExample()
{
myBoolean1 = true;
myBoolean2 = true;
}
//...
Singleton is an antipattern, but if you feel you must use it, implement it using an enum.