开发者

Are immutable objects always threadsafe?

It is safe to assume that working with or passing around an immu开发者_如何学Ctable 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!)

What do I mean by "internal mutations"?

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).


That depends what you mean by threadsafe; as Eric Lippert's blog points out, the term can mean several things. Immutable objects guarantee that no matter when you access a property or method on a given instance, the result will always be the same; this is thread safety across that instance. However, if you have a mutable field containing a reference to an immutable object then multiple calls via the same field may not be to the same instance, hence are not consistent (i.e. "threadsafe").

I suspect that for the meaning of "threadsafe" that you have in mind, the answer is yes. But keep in mind that immutable objects aren't a golden bullet; they don't make you immune to thread interactions, they just provide consistency across a single instance.


To answer the question correctly: No.

You can't assume that immutable objects are always threadsafe.

But most probably are. See also the discussion on Lukes answer.

For instance: access to methods or property getters could trigger initialization, which is not known by the caller. (Eg. lazy initialization) This initialization must be implemented explicitly threadsafe.


First the object must be truly immutable - not just the public interface but all internal state must be as initialized. This prohibits e.g. "get once then cache" or deferred initialization.

Second, during construction, the objects are modified - and due to optimizations and instruction reordering on the CPU the order in which memory is written is not necessarily the same order you see in the source code.

This means that, without synchronization, another thread may already see a valid reference to the object before it is constructed completely.

I am not familiar enough with the C# memroy model to tell you exactly which synchronization is necessary - maybe someone else can help (made community wiki)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜