必须是不可变对象的所有属性都是最终的吗?

DRa*_*lav 49 java final immutability java-memory-model

必须是不可变对象的所有属性都是final

据我说不.但我不知道,我是否正确.

ass*_*ias 53

不可变对象(所有属性final)和有效不可变对象(属性不是final但不能更改)之间的主要区别是安全发布.

您可以安全地在多线程上下文中发布不可变对象,而不必担心添加同步,这要归功于Java内存模型为最终字段提供保证:

final字段还允许程序员在没有同步的情况下实现线程安全的不可变对象.线程安全的不可变对象被所有线程视为不可变的,即使使用数据争用传递线程之间的不可变对象的引用也是如此.这可以提供安全保证,防止错误或恶意代码滥用不可变类.必须正确使用最终字段以提供不可变性的保证.

作为旁注,它还可以强制实现不变性(如果您尝试在类的未来版本中改变这些字段,因为您忘记它应该是不可变的,它将无法编译).


澄清

  • 使对象的所有字段最终不会使其不可变 - 您还需要确保(i)其状态不能更改(例如,如果对象包含一个final List,没有变异操作(添加,删除......) )必须在施工后完成)和(ii)this在施工期间不要逃生
  • 一旦安全发布,有效不可变对象就是线程安全的
  • 不安全发布的示例:

    class EffectivelyImmutable {
        static EffectivelyImmutable unsafe;
        private int i;
        public EffectivelyImmutable (int i) { this.i = i; }
        public int get() { return i; }
    }
    
    // in some thread
    EffectivelyImmutable.unsafe = new EffectivelyImmutable(1);
    
    //in some other thread
    if (EffectivelyImmutable.unsafe != null
        && EffectivelyImmutable.unsafe.get() != 1)
        System.out.println("What???");
    
    Run Code Online (Sandbox Code Playgroud)

    该程序理论上可以打印What???.如果i是最终的,那将不是一个合法的结果.

  • 如果它们的所有字段均为最终字段,则仍然可以安全地发布它们,但这不足以使它们安全。 (2认同)

mil*_*ose 15

您可以通过单独封装轻松保证不变性,因此没有必要:

// This is trivially immutable.
public class Foo {
    private String bar;
    public Foo(String bar) {
        this.bar = bar;
    }
    public String getBar() {
        return bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在某些情况下,您还必须通过封装保证它,因此这还不够:

public class Womble {
    private final List<String> cabbages;
    public Womble(List<String> cabbages) {
        this.cabbages = cabbages;
    }
    public List<String> getCabbages() {
        return cabbages;
    }
}
// ...
Womble w = new Womble(...);
// This might count as mutation in your design. (Or it might not.)
w.getCabbages().add("cabbage"); 
Run Code Online (Sandbox Code Playgroud)

这样做是为了捕捉一些微不足道的错误并清楚地表明你的意图并不是一个坏主意,但"所有字段都是最终的"和"类是不可变的"不是等同的陈述.


Kai*_*Kai 6

不可变=不可改变.因此,使属性最终是一个好主意.如果没有保护对象的所有属性都不被改变,我不会说该对象是不可变的.

但是如果一个对象没有为它的私有属性提供任何setter,那么它也是不可变的.


Eug*_*ene 5

不可变对象在创建后不得以任何方式进行修改.最终当然有助于实现这一目标.您保证永远不会更改它们.但是,如果你的对象中有一个最终的数组怎么办?当然,引用不是可更改的,但元素是.看看我给出的几乎相同的问题:

链接


小智 5

简单地声明一个对象final并不会使它本身不可变.就拿这个:

import java.util.Date;

/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/
public final class Planet {

  public Planet (double aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     //make a private copy of aDateOfDiscovery
     //this is the only way to keep the fDateOfDiscovery
     //field private, and shields this class from any changes that 
     //the caller may make to the original aDateOfDiscovery object
     fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
  }

  /**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */
  public double getMass() {
    return fMass;
  }

  /**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */
  public String getName() {
    return fName;
  }

//  /**
//  * Returns a mutable object - likely bad style.
//  *
//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
//  * since the Date object state can be changed both by this class and its caller.
//  * That is, this class is no longer in complete control of fDate.
//  */
//  public Date getDateOfDiscovery() {
//    return fDateOfDiscovery;
//  }

  /**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */
  public Date getDateOfDiscovery() {
    return new Date(fDateOfDiscovery.getTime());
  }

  // PRIVATE //

  /**
  * Final primitive data is always immutable.
  */
  private final double fMass;

  /**
  * An immutable object field. (String objects never change state.)
  */
  private final String fName;

  /**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */
  private final Date fDateOfDiscovery;
}
Run Code Online (Sandbox Code Playgroud)