Java : Why does placement of static variable matter?

时间:2019-04-08 14:01:59

标签: java static

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?

2 个答案:

答案 0 :(得分:10)

myBoolean2在构造函数中被设置为true后,由于静态变量初始化的顺序而被重新设置为false。

  

使用静态变量时是否有“规则”?

是的。静态单例不需要静态。只需将它们设置为常规字段即可。

private static volatile MySingletonExample instance = new MySingletonExample();

private final boolean myBoolean1;
private final boolean myBoolean2;

private MySingletonExample()
{
    myBoolean1 = true;
    myBoolean2 = true;
}

//...

Singleton是一种反模式,但是如果您必须使用它,implement it using an enum

答案 1 :(得分:5)

该块中的所有静态变量均按顺序执行。因此,首先将myBoolean1设置为false,然后调用MySingletonExample()构造函数,该构造函数将myBoolean1myBoolean2设置为true。最后,myBoolean2设置为false

它们必须以某种确定性的顺序被调用,否则就不可能对程序的行为进行推理。

相关问题