我有一个不可变的对象,它的字段或类没有标记为final。我可以这样做,但是这样做真的有什么好处吗?我可以看到它为编译器节省了一些时间来解决问题,但我看不出它“值得”(除此之外,它将使 future 的开发人员重新考虑对对象做一些事情以使其可变) .
最佳答案
除了您提出的观点( future 的开发人员修改字段是一个非常明智的观点,另一个观点是有人可以对您的类进行子类化并使其可变),显式地将字段标记为 Final 可以为您提供多方面的可见性保证。线程环境。
以这个类为例 - 它实际上是不可变的:
public class SomeClass {
private int i;
public SomeClass(int i) { this.i = i; }
public int getI() { return this.i; }
}
在多线程环境中,线程 T1 有可能创建 SomeClass sc = new SomeClass(1);
而另一个线程 T2 读取 sc.getI()
并看到 0。
如果 i
被最终确定,这种情况就不会再发生了(假设您在构造过程中不让 this
逃逸,如下面的引用中所述)。
引用:JLS #17.5 - 强调我的
final fields also allow programmers to implement thread-safe immutable objects without synchronization. [...]
The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields.
关于java - 将 java 对象标记为final(实际上是final的)有什么好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992086/