`
wjm251
  • 浏览: 108476 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

<Java concurrency in practice>说这个代码不安全,记一下,慢慢理解

    博客分类:
  • java
阅读更多
class Holder {
    private int n;

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

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

public class test {
    public Holder holder;

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

}
======================================
当再有另外一个线程B(即不同于new Holder的这个线程A)调用assertSanity,居然有可能抛出异常来。还说如果把Holder中的n标为final就可以解决,

当然,如果想B线程即时看到A线程对holder的改动,holder还是需要定为volatile的。
太神奇了,照这本书里的这些说法,公司系统里头的代码简直全是隐患啊,只是碰巧能工作,说不定啥时候就爆出个莫名其妙的问题来。

以下是书中描述的final的特殊功效。
===========================
but they also have special semantics under the Java Memory Model. It is the use of final fields that makes possible the guarantee of initialization safety (see Section 3.5.2) that lets immutable objects be freely accessed and shared without synchronization.
分享到:
评论
1 楼 a999888huang 2015-09-25  
这个极难重现。。。
虽然根据Java® Language Specification 8th 的
https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4
17.5 的An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

说明它不是final的可能会问题。不过,至少是百万级的。

相关推荐

Global site tag (gtag.js) - Google Analytics