Question

If I have this:

public class Foo {
    public int bar;

    public Foo(int bar) {
        this.bar = bar;

        synchronized (Foo.class) {
            Foo.instance = this;
            Foo.class.notify();
        }
    }

    public static Foo instance;

    public static Foo instance() {
        synchronized (Foo.class) {
            if (Foo.instance == null) {
                Foo.class.wait();
            }

            return instance;
        }
    }
}

And in another class I have this, at any and all unspecified points in the future, assuming I have NOT yet altered the value of Bar by any means:

int baz = Foo.instance().bar;

Is there any possibility at all of having Foo . Instance ( ) . Bar return uninitialized gibberish? My thought is that, since I have assured that nothing will ever try to access Bar before the Instance variable is set, that the JIT compiler cannot optimize away anything and must read from main memory, but is this true? Is it possible for it to somehow get compiled so that it instead pulls 0 (which was the value of Bar before it was set to the new value in the constructor).

Was it helpful?

Solution

There are many ways to implement singleton - this one is the most odd I have ever seen. If it's not singleton - note that two instances of this class cannot be used concurrently.

If you use only one instance of this class it will not return any gibber if only variable Bar is declared as volatile in this case. Otherwise strange things, such as 0-returns can occur.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top