开发者

Is the ordering of static members sensitive in Swing?

I have this class, let's say, Foo. It extends JFrame and is a singleton. That being said, it has two static fields: 1) an instance of Foo and 2) a Color.

Here's a code snippet of Foo:

public class Foo extends JFrame{
    private static final Color FOO_RED = new Color(155, 64, 69);
    private static final Foo INSTANCE = new Foo();

    private Foo(){
        //do stuff
    }

    public static Foo getInstance(){
        return INSTANCE;
    }
}

I also have another class, let's say, Launcher. This is the main class that is responsible for launching the application. It's a simple class in that its only job is to delegate the task of constructing Foo to the EDT.

Here's a code snippet of Launcher:

public class Launcher{
    public static void main(String[] args){
        SwingUtilities.invokeLater((new Runnable(){
            @Override
            public void run()
            {
                Foo.getInstance();
            }
        }));
    }
}

Now, this all works just fine. But, when I switch the ordering of Foo's fields (See below), the components that use FOO_RED are no longer painted this color.

public class Foo extends JFrame{
    private static final Foo INS开发者_C百科TANCE = new Foo(); //declared before Color
    private static final Color FOO_RED = new Color(155, 64, 69);

    private Foo(){
        //do stuff
    }

    public static Foo getInstance(){
        return INSTANCE;
    }
}

So, this begs the question, does the ordering of static fields matter when it comes to Swing?


As already mentioned, ordering of static fields does matter. Executed in the order they appear.

I would make another change to this example. This would make you static field order less important.

UPDATE: Use IDOH (Initialization on Demand Holder) pattern to make singleton thread safe.

private static class FooHolder {
    private static final Foo INSTANCE = new Foo();
}

public static Foo getInstance(){
    return FooHolder.INSTANCE;
}


Yes. ordering matters for any static fields/blocks.


EDIT: First, static fields are set to their default value(So FOO_RED is null).then the static fields are initialized in the order it appears. so it is possible to observe the FOO_RED field before it is initialized.


The ordering does matter for static fields, as they are initialized from top to bottom. In your case, switching the order causes the Foo() constructor to be called before the initialization of FOO_RED. As such, FOO_RED will be null for use within the constructor. This is legal, though obviously of no use to any controls that would like to use FOO_RED.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜