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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With