Alex Rivera | Logout

Not thread-safe Object publishing

Asked 2009-10-25T17:11:36.440
17

Reading "Java Concurrency In Practice", there's this part in section 3.5:

public Holder holder;
public void initialize() {
     holder = new Holder(42);
}

Besides the obvious thread safety hazard of creating two instances of Holder, the book claims a possible publishing issue can occur.

Furthermore, for a Holder class such as

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

an AssertionError can be thrown!

How is this possible? The only way I can think of that can allow such ridiculous behavior is if the Holder constructor would not be blocking, so a reference would be created to the instance while the constructor code still runs in a different thread.

Is this possible?

Edit
Report

1 Answer

-2

looking at this from a sane perspective, if you assume that the statement

if(n != n)

is atomic (which I think is reasonable, but i dont know for sure), then the assertion exception could never be thrown.

answered 2009-10-25T17:21:08.963

Your Answer