不可变对象和有效不可变对象之间的区别? [英] Different between immutable and effectively immutable objects?

查看:157
本文介绍了不可变对象和有效不可变对象之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Java Concurrency in Practice中的一句话

共享的只读对象包括不可变的和有效的不可变的 对象.

不可变对象和有效不可变对象之间有什么区别?

解决方案

该类的实例不可扩展,且其字段均为final并且自身不可变,它们是不可变的.

由于其方法的详细信息而无法更改其字段的类的实例实际上是不可变的.例如:

final class C {
  final boolean canChange;
  private int x;
  C(boolean canChange) { this.canChange = canChange; }
  public void setX(int newX) {
    if (canChange) {
      this.x = newX;
    } else {
      throw new IllegalStateException();
    }
  }
}

C的某些实例实际上是不可变的,而有些则不是.

另一个例子是零长度数组.它们实际上是不可变的,即使它们的包含类不是可证明的不可变的,因为它们中没有元素可以更改.


Joe-E使用验证程序来证明某些类仅允许不可变的实例.带有 Immutable 标记接口,并将某些类(如String(由于其char[]不会逸出,因此实际上是不可变的))作为不可变的.

Joe-E:Java的面向安全的子集

由Joe-E库定义的Immutable接口, 该语言经过特殊处理:Joe-E验证程序 检查实现此接口的每个对象是否都将 是(深层)不可变的,并且在以下情况下产生编译时错误: 无法自动验证.

This is a sentence from Java Concurrency in Practice

Shared read-only objects include immutable and effectively immutable objects.

What are the differences between immutable and effectively immutable objects?

解决方案

Instances of a class that is not extensible and whose fields are all final and themselves immutable are immutable.

Instances of a class whose fields cannot be mutated because of details of its methods are effectively immutable. For example:

final class C {
  final boolean canChange;
  private int x;
  C(boolean canChange) { this.canChange = canChange; }
  public void setX(int newX) {
    if (canChange) {
      this.x = newX;
    } else {
      throw new IllegalStateException();
    }
  }
}

Some instances of C are effectively immutable and some are not.

Another example is zero-length arrays. They are effectively immutable even though their containing class is not provably immutable since there is no element of them which can be changed.


Joe-E uses a verifier to prove that some classes only allow for immutable instances. Anything marked with the Immutable marker interface are checked and certain classes like String (effectively immutable since its char[] does not escape) are grandfathered in as immutable.

Joe-E: A Security-Oriented Subset of Java says

The Immutable interface, defined by the Joe-E library, is treated specially by the language: the Joe-E verifier checks that every object implementing this interface will be (deeply) immutable, and raises a compile-time error if this cannot be automatically verified.

这篇关于不可变对象和有效不可变对象之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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