多线程应用程序中的不可变对象-它如何工作?

dim*_*tar 5 java concurrency multithreading object immutability

我有这段代码将在多线程应用程序中工作。我知道不可变对象是线程安全的,因为它的状态无法更改。如果我们有可变引用,则用例如MyImmutableObject state = MyImmutableObject.newInstance(oldState,newArgs)进行更改。例如,如果一个线程想要更​​新状态,则它必须创建一个新的不可变对象,并使用旧状态和一些新的状态参数对其进行初始化),这对于所有其他线程都是可见的。但是问题是,如果一个线程2开始对该状态进行长时间操作,那么在哪个线程1中使用新实例更新该状态的情况下,将会发生什么?Thread2将使用对旧对象状态的引用,即它将使用不一致的状态吗?否则线程2将看到线程1所做的更改,因为对状态的引用是易变的,

State state = cache.get(); //t1 
Result result1 = DoSomethingWithState(state); //t1 
        State state = cache.get(); //t2
    ->longOperation1(state); //t1
        Result result2 = DoSomethingWithState(state); //t2
             ->longOperation1(state); //t2
   ->longOperation2(state);//t1
cache.update(result1); //t1 
             ->longOperation2(state);//t2
        cache.update(result2);//t2

Result DoSomethingWithState(State state) {
    longOperation1(state);
    //Imaging Thread1 finish here and update state, when Thread2 is going to execute next method
    longOperation2(state);
return result;
}

class cache {
     private volatile State state = State.newInstance(null, null);

    update(result) {
        this.state = State.newInstance(result.getState, result.getNewFactors);

    get(){
       return state;
    }

 }
Run Code Online (Sandbox Code Playgroud)

tra*_*god 1

\n

但引用是volatile,它不是使新对象状态 \xe2\x80\xa6 对其他线程可见吗?

\n
\n\n

不会。虽然对该volatile字段的写入发生在该字段的每次后续读取之前,但另一个线程必须重新读取该字段才能获取新值。

\n