Documentation

The Java™ Tutorials
Hide TOC
Immutable Objects不变对象
Trail: Essential Java Classes
Lesson: Concurrency

Immutable Objects不变对象

An object is considered immutable if its state cannot change after it is constructed. 如果对象的状态在构造后无法更改,则认为该对象是不可变的。Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.最大限度地依赖不可变对象被广泛认为是创建简单、可靠代码的合理策略。

Immutable objects are particularly useful in concurrent applications. 不可变对象在并发应用程序中特别有用。Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.因为它们不能改变状态,所以它们不能被线程干扰破坏,也不能在不一致的状态下被观察到。

Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. 程序员通常不愿意使用不可变对象,因为他们担心创建新对象的成本,而不是就地更新对象。The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. 对象创建的影响常常被高估,并且可以被与不可变对象相关的一些效率所抵消。These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.其中包括由于垃圾收集而减少的开销,以及消除保护可变对象免受损坏所需的代码。

The following subsections take a class whose instances are mutable and derives a class with immutable instances from it. 以下小节将获取一个实例可变的类,并从该类派生一个实例不可变的类。In so doing, they give general rules for this kind of conversion and demonstrate some of the advantages of immutable objects.在此过程中,他们给出了这种转换的一般规则,并展示了不可变对象的一些优点。


Previous page: Guarded Blocks
Next page: A Synchronized Class Example