具有非最终成员且没有mutator方法的类的线程安全 [英] Thread safety for classes with non-final members with no mutator methods
问题描述
对于以下课程,使mNumSides
最终的含义是什么? 线程安全性"会受到影响吗?
For the following class, what are the implications of making mNumSides
final? Is "thread-safety" affected?
class Shape {
private int mNumSides;
public Shape(int numSides) {
mNumSides = numSides;
}
public int getNumSides() {
return mNumSides;
}
}
推荐答案
绝对. final
关键字保证所有线程始终都看到相同的mNumSides
值.关于final
及其对内存模型的影响的更多信息
Absolutely. final
keyword guarantees that all the threads see the same value of mNumSides
at all the times. More information on final
and its impact on the Memory Model here.
在不使用final
的情况下,该对象可能会不一致地发布到其他线程,并且有可能(虽然非常低)线程可能将mNumSides
的值视为0
而不是传入的numSides
构造函数.
将其设置为volatile
或static
也可以.
Without using final
the object might be inconsistently published to other threads, and there is probability (extremely low though) that a thread might see the value of mNumSides
as 0
rather than numSides
as passed in constructor.
Making it volatile
or static
will also work though.
这篇关于具有非最终成员且没有mutator方法的类的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!