1

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?

Unhandled Exception
  • 1,427
  • 14
  • 30
  • 1
    Possible duplicate of [Order of static variable initialization, Java](https://stackoverflow.com/questions/13554507/order-of-static-variable-initialization-java) – noiaverbale Apr 08 '19 at 14:06

2 Answers2

9

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.

Michael
  • 41,989
  • 11
  • 82
  • 128
5

All the statics in the block get executed in-order. So first myBoolean1 is set to false, then comes the call to the MySingletonExample() constructor, which sets myBoolean1 and myBoolean2 to true. Finally, myBoolean2 is set to false.

There needs to be some deterministic order in which they get invoked, otherwise it would be impossible to reason about the behavior of the program.