Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety on readonly static field initialisation

Tags:

If one creates a readonly static member like this:

public sealed class MyClass {     public readonly static MyClass Instance = new MyClass(); } 

We know that the static constructor will initialise the MyClass.Instance field if some thread accesses MyClass the fist time. But, will a single instance (in this case MyClass) be created if multiple threads all accesses MyClass at the same time (i.e. is the initialisation of the static field thread-safe)?

like image 221
Francois Nel Avatar asked Aug 28 '12 12:08

Francois Nel


People also ask

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 static fields thread safe?

In other words, static fields are not thread safe. Only final fields are thread safe. For both instance and static fields that are not final, you have to access them within synchronized methods/statements or using the concurrent lock feature available in Java 7/8.

Are static fields thread safe C#?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.

Is static initialization thread safe Java?

Yes, Java static initializers are thread safe (use your first option). However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.


2 Answers

.NET CLR ensures that static initialization is always thread-safe. No matter how many threads are accessing it and what order, it will always be initialized once.

Your code seems to show signs of the beginnings of a Singleton pattern.
Basically if you want to run custom code before you initialize the class, then you need to ensure thread-safety on your own.
This is an example where you would need to make your custom code thread safe. But the static initialization part is always thread safe.

like image 85
Kash Avatar answered Sep 20 '22 14:09

Kash


The class initialization is guaranteed by the specification of the C# language to be thread safe, so only one instance of MyClass will be created. You would have to ensure thread safety from that point onwards yourself. Here's an MSDN reference:

http://msdn.microsoft.com/en-us/library/aa645612.aspx

like image 23
David M Avatar answered Sep 20 '22 14:09

David M