Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

java - Not thread-safe Object publishing

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason why this is possible is that Java has a weak memory model. It does not guarantee ordering of read and writes.

This particular problem can be reproduced with the following two code snippets representing two threads.

Thread 1:

someStaticVariable = new Holder(42);

Thread 2:

someStaticVariable.assertSanity(); // can throw

On the surface it seems impossible that this could ever occur. In order to understand why this can happen, you have to get past the Java syntax and get down to a much lower level. If you look at the code for thread 1, it can essentially be broken down into a series of memory writes and allocations:

  1. Alloc memory to pointer1
  2. Write 42 to pointer1 at offset 0
  3. Write pointer1 to someStaticVariable

Because Java has a weak memory model, it is perfectly possible for the code to actually execute in the following order from the perspective of thread 2:

  1. Alloc Memory to pointer1
  2. Write pointer1 to someStaticVariable
  3. Write 42 to pointer1 at offset 0

Scary? Yes but it can happen.

What this means though is that thread 2 can now call into assertSanity before n has gotten the value 42. It is possible for the value n to be read twice during assertSanity, once before operation #3 completes and once after and hence see two different values and throw an exception.

EDIT

According to Jon Skeet, the AssertionError migh still occur with Java 8 unless the field is final.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...