How can an immutable object, with non-final fields, be thread unsafe?

后端 未结 4 782
栀梦
栀梦 2021-01-02 13:06

say we have this

// This is trivially immutable.
public class Foo {
    private String bar;
    public Foo(String bar) {
        this.bar = bar;
    }
    pu         


        
4条回答
  •  一个人的身影
    2021-01-02 13:23

    Foo is thread safe once it has been safely published. For example, this program could print "unsafe" (it probably won't using a combination of hotspot/x86) - if you make bar final it can't happen:

    public class UnsafePublication {
    
        static Foo foo;
    
        public static void main(String[] args) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (foo == null) {}
                    if (!"abc".equals(foo.getBar())) System.out.println("unsafe");
                }
            }).start();
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    foo = new Foo("abc");
                }
            }).start();
        }
    }
    

提交回复
热议问题