我有这段代码可以在多线程应用程序中工作。 我知道不可变对象(immutable对象)是线程安全的,因为它的状态不能改变。如果我们有 volatile 引用,则 if 被更改为例如 MyImmutableObject state = MyImmutableObject.newInstance(oldState, newArgs);也就是说,如果一个线程想要更新状态,它必须创建新的不可变对象(immutable对象),用旧状态和一些新状态参数初始化它)并且这对所有其他线程都是可见的。 但问题是,如果一个线程 2 开始对状态进行长时间操作,中间线程 1 用新实例更新状态,会发生什么? Thread2 将使用对旧对象状态的引用,即它将使用不一致的状态?或者线程 2 将看到线程 1 所做的更改,因为对状态的引用是易变的,在这种情况下,线程 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;
}
}
最佳答案
But the reference is
volatile
, isn't it making visible the new object state … to the other threads?
没有。在写入 volatile
字段时 happens-before每次后续读取该字段时,另一个线程都必须重新读取该字段以获取新值。
关于java - 多线程应用程序中的不可变对象(immutable对象) - 它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803487/