Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is readonly variable thread safe? [duplicate]

Possible Duplicate:
Is a readonly field in C# thread safe?

A quite simple program

private readonly string _data1;
private readonly int _data2;
private readonly MyAnotherClass _data3;

public MyClass(string data1, int data2, MyAnotherClass data3)
{
    _data1 = data1;
    _data2 = data2;
    _data3 = data3;
}

Are _data1, _data2 and _data3 thread safe?

like image 293
Alexandre Avatar asked Nov 13 '12 02:11

Alexandre


People also ask

Is reading variables thread-safe?

No this operation is not inherently thread safe. Even though the variable is not currently being written to, previous writes to the variable may not yet be visible to all threads. This means two threads can read the same value and get different results creating a race condition.

Is static readonly thread-safe?

Only the initialization of static fields are thread safe, the value is not! To guarantee thread safety on static fields, add readonly (read initonly). This guarantees that the value cannot be overwritten (if you are not using a collection of some sort that is).

Are private variables thread-safe?

On its stack(basically thread stack), local primitives and local reference variables are stored. Hence one thread does not share its local variables with any other thread as these local variables and references are inside the thread's private stack. Hence local variables are always thread-safe.

Which variables are thread-safe?

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.


1 Answers

A read-only variable is guaranteed to be initialized before it is accessed. The initial value is assigned during construction of the object, before the object is fully allocated.

Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.

Reference: C# Spec, 10.11.3 Constructor execution (emphasis mine)

Assignment to a readonly field can only occur as part of the field’s declaration or in a constructor in the same class

Reference: C# Spec, 1.6.5 Fields

For that reason, the value will be set before it is available to any thread, and will not change, so it is thread safe.

like image 191
Eric J. Avatar answered Oct 13 '22 12:10

Eric J.