The Java™ Tutorials — Concurrency :Immutable Objects 不可变对象

The Java™ Tutorials — Concurrency :Immutable Objects 不可变对象

原文地址:https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html

关键点

  • 并发环境中,不可变对象十分有用。由于它们的状态不可变,也就因此不会陷入到线程冲突,或读取结果不定的问题之中。

全文翻译

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.

下面几个子章节中,我们会拿一个其实例可变的类,并根据其派生一个具有不可变实例的类。这样的做法会引出此类变换的一般规则,以及说明不可变对象的一些优势特性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值