Alex Rivera | Logout

Why are immutable objects thread-safe?

Asked 2010-08-29T14:28:53.967
35
class Unit {
    private readonly string name;
    private readonly double scale;

    public Unit(string name, double scale) {
        this.name = name;
        this.scale = scale,
    }

    public string Name { get { return name; } }
    public string Scale { get { return scale; } }

    private static Unit gram = new Unit("Gram", 1.0);

    public Unit Gram { get { return gram; } }
}

Multiple threads have access to Unit.Gram. Why is it ok for multiple threads simultaneously read Unit.Gram.Title?

My concern is that they are referring to the same memory location. One thread starts reading that memory, so isn't it "locked out" then? Does the .NET handle synchronization for this critical section underneath? Or am I wrong in thinking that simultaneous reading needs synchronization?

Edit
Report

2 Answers

11

Simultaneous reads do not need synchronization. Since synchronization is only required for writers (or readers and at least one writer), immutable objects don't require synchronization, and are therefor threadsafe.

answered 2010-08-29T14:38:00.860
3

Concurrent reads do not require synchronization in the vast majority of cases (exceptions are things like memory mapped IO where reading from a certain address can cause side effects).

If concurrent reads did require synchronization, it would be close to impossible to write usefully multi-threaded code. To execute a piece of code for instance, the processor has to read the instruction stream, how would you write a lock function if the function itself had to protect against itself being executed concurrently :)?

answered 2010-08-29T14:39:00.103

Your Answer