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

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

    Due to JVM optimization, you can never assume that operations are executed in the order they are written, unless it matters for the same thread. So when you call the constructor and then pass a reference to the resulting object to another thread, the JVM might not actually write the value of foo.bar before it is needed within the same thread.

    That means that in a multithreaded environment, the getBar method could be called before the value in the constructor was written to it.

提交回复
热议问题