Everybody says that immutable objects are thread safe, but why is this?
Take the following scenario running on a multi core CPU:
- Core 1 reads an object at memory location
0x100
and it is cached in the L1/L2 cache of Core 1; - The GC collects this object at that memory location because it has become eligible and
0x100
becomes available for new objects; - Core 2 allocates an (immutable) object which is located at address
0x100
; - Core 1 gets a reference to this new object and reads it at memory location
0x100
.
In this situation, when Core 1 asks for the value at location 0x100
is it possible that it reads the stale data from its L1/L2 cache? My intuition says that a memory gate is still needed here to ensure that Core 1 reads the correct data.
Is the above analysis correct and is a memory gate required, or am I missing something?
UPDATE:
The situation I describe here is a more complex version of what happens every time the GC does a collect. When the GC collects, memory is reordered. This means that the physical location the object was located at changes and that L1/L2 must be invalidated. Roughly the same applies to the example above.
Since it is reasonable to expect that .NET ensures that after reordering memory, different cores see the correct memory state, the above situation will not be a problem too.