使用不可变对象在Java中的优点和缺点

Advantages
1 An immutable object remains in exactly one state, the state in which it was created. Therefore, immutable object is thread-safe so there is no synchronization issue. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety.
不可变对象至表示一个状态。所以线程安全没有同步问题。
2 Immutable classes are easier to design, implement, and use than mutable classes.
不可变对象更加易于设计、实现和使用。
3 Immutable objects are good Map keys and Set elements, since these typically do not change once created.
不可变对象是很优秀的Map key和Set element。
4 Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).
不可变性使得编写、使用和解释代码很容易。
5 Immutability makes it easier to parallelize program as there are no conflicts among objects.
不可变性是得并行变得容易,因为没有冲突。
6 The internal state of program will be consistent even if you have exceptions.
程序被状态不会发生改变,就算有异常发生。
7 References to immutable objects can be cached as they are not going to change. (i.e. in Hashing it provide fast operations).
不可变对象的引用可以被缓存。

Disadvantages
Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections. The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
创建一个不可变对象似乎是一件很美妙的事情。但是当你需要修改对象的时候,你需要首先创建一个新的对象。会无形中增加GC的负担。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值