Site Search:

StuffIntoPublic.java

<Back

Multi-thread's visibility challenge has two aspects: threads can see the object in its as-published state; the modifications are visible after publication. 

The first aspect are often ignored by developers. An object is in a predictable, consistent state only after its constructor returns, however in multi-threading environment, one thread could be in the middle of running a class's static initializer, instance initializer or constructor, when another thread references the object or its state variables. In that case, the consuming thread will see an partially constructed object and get screwed. 

The initialization hazards won't happen easily, your (single core cpu) machine need to reorder your code, and the chance of screw up is slim, however, it is there, so don't ignore it.



StuffIntoPublic.java

public class StuffIntoPublic {
    public Holder holder; //null

    public void initialize() {
        holder = new Holder(42);
    }
    
    public static void main(String...args) {
        StuffIntoPublic t = new StuffIntoPublic();
        t.initialize();
        new Thread(new Runnable(){
            @Override
            public void run() {
                //holder is null
                //n as 0
                //n first read as 0, n second read as 42
                //n as 42 (99.999999999...% of the time)
                t.holder.assertSanity();
            }}).start();
    }
}

class Holder {
    private int n;//0

    public Holder(int n) {
        this.n = n;
    }

    public void assertSanity() {
        if (n != n)
            throw new AssertionError("This statement is false.");
    }
}