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

后端 未结 4 597
栀梦
栀梦 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:06

    From the link posted in comments:

    class FinalFieldExample { 
        final int x;
        int y; 
        static FinalFieldExample f;
    
        public FinalFieldExample() {
            x = 3; 
            y = 4; 
        } 
    
        static void writer() {
            f = new FinalFieldExample();
        } 
    
        static void reader() {
            if (f != null) {
                int i = f.x;  // guaranteed to see 3  
                int j = f.y;  // could see 0
            } 
        } 
    }
    

    One thread may call writer() and and another thread may call reader(). The if condition in reader() could evaluate to true, but becuase y is not final the object initalizion may not have completely finished (so the object has not been safely published yet), and thus int j = 0 could happen as it has not been initialized.

提交回复
热议问题