在Java中不可变 [英] Immutable in java

查看:153
本文介绍了在Java中不可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有效的Java 中,Bloch建议将所有字段最终确定为对象不可变.

In Effective Java, Bloch recommends to make all the fields final in making an object immutable .

是否有必要这样做?不只是不提供访问器方法就使其不可变.

Is it necessary to do so ? Won't just not giving accessor methods make it immutable.

例如

class A {
      private int x;
      A (int x) {
          this.x = x;
      }
}

即使我没有将x声明为final,上述类也是不可变的?我想念什么吗?

The above class is immutable even if I don't declare x as final right ? Am I missing something ?

推荐答案

除了@Bozho的要点之外,将字段声明为final意味着可以安全地访问该字段而无需任何同步.

In addition to @Bozho's point, declaring a field as final means that it can be safely accessed without any synchronization.

相反,如果该字段不是final,则存在另一个风险,即如果另一个线程在没有适当同步的情况下对其进行访问,则另一个线程将看到该字段的异常值.即使在对象构建后没有任何改变字段值的情况,也会发生这种情况!

By contrast, if the field is not final there is a small risk that another thread will see an anomalous value for the field if it accesses it without proper synchronization. This can happen even if nothing changes the field's value after object construction!

这篇关于在Java中不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆