不可变对象是否始终是线程安全的? [英] Are immutable objects always threadsafe?

查看:287
本文介绍了不可变对象是否始终是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以肯定地认为使用或传递不可变对象始终是线程安全的吗?

It is safe to assume that working with or passing around an immutable object would always be threadsafe?

推荐答案

是.如果对象确实是不可变的,没有发生内部变异,则该对象本身将是线程安全的.

Yes. If an object is truly immutable, with no internal mutations occurring, then the object itself will be threadsafe.

(是否处理该对象并以线程安全的方式传递它是另一回事!)

(Whether you handle the object and pass it around in a threadsafe manner is another matter!)

内部突变"是什么意思?

许多对象似乎从外部是不可变的-例如,没有属性设置器或其他会明显地触发突变的成员-但这并不意味着该对象的私有内部不存在.能够改变.

Many objects appear to be immutable from the outside - for example, no property setters or other members that would obviously trigger mutations - but that doesn't mean that the private internals of the object aren't capable of changing.

这就是为什么记录您的对象和/或其成员的可变性和线程安全性很重要的原因.否则,您的对象的使用者就无法在不仔细检查内部信息的情况下发现此信息(内部信息是一种实现细节,并且随时可能更改).

That's why it's important to document the mutability and thread-safety of your objects and/or their members. Otherwise there's no way for consumers of your object to discover this without closely examining the internals (which are an implementation detail and could change at any time).

这篇关于不可变对象是否始终是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆