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

时间:2013-04-17 13:13:30

标签: java immutability final java-memory-model

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

根据我没有。但我不知道,我是否正确。

8 个答案:

答案 0 :(得分:52)

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

由于guarantees provided by the Java Memory Model for final fields,您可以安全地在多线程上下文中发布不可变对象,而不必担心添加同步:

  

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???");
    

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

答案 1 :(得分:15)

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

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

但是,在某些情况下,必须通过封装来保证它,所以它不是足够的

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"); 

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

答案 2 :(得分:5)

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

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

答案 3 :(得分:5)

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

Link

答案 4 :(得分:5)

简单地将对象声明为final并不会使其本身不可变。以此为例class

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;
}

答案 5 :(得分:2)

没有

例如,请参阅java.lang.String的实现。字符串在Java中是不可变的,但字段hash不是 final (它是在第一次调用hashCode然后缓存时懒惰计算的)。但这是有效的,因为hash只能在每次计算时使用一个非默认值。

答案 6 :(得分:2)

String类是Immutable但属性hash不是final

有可能但是有一些规则/限制,并且访问可变属性/字段必须在每次访问时提供相同的结果。

在String类中,哈希码实际上是在最终的字符数组上计算的,如果String构造的话,这些字符不会改变。因此,不可变类可以包含可变字段/属性,但它必须确保每次访问时对字段/属性的访问都会产生相同的结果。

要回答您的问题,并非必须将所有字段设置为不可变类中的最终字段。

如需进一步阅读,请访问[blog]:http://javaunturnedtopics.blogspot.in/2016/07/string-is-immutable-and-property-hash.html

答案 7 :(得分:0)

不是必需的,您可以通过将成员设置为非最终成员但私有并将其修改(除非在构造函数中)来实现相同的功能。不要为它们提供setter方法,如果它是一个可变对象,则不要泄漏该成员的任何引用。

请记住将引用变量定为final,仅确保不会将其重新分配其他值,但是您仍然可以更改该引用变量所指向的对象的各个属性。这是关键点之一。