Are static variables thread-safe? C# - c#

I want to create a class which stores DataTables, this will prevent my application to import a list of details each time I want to retrieve it. Therefore this should be done once, I believe that the following code does so, but I am not sure if it is thread-safe.
The below code is in the Business Layer Section of my three tier application, it is returning a DataTable to the Presentation Layer.
public class BusinessLayerHandler
{
public static DataTable unitTable;
public static DataTable currencyTable;
public static DataTable GetUnitList()
{
//import lists each time the application is run
unitTable = null;
if (unitTable == null)
{
return unitTable = DatabaseHandler.GetUnitList();
}
else
{
return unitTable;
}
}
public static DataTable GetCurrencyList()
{
//import lists each time the application is run
currencyTable = null;
if (currencyTable == null)
{
return currencyTable = DatabaseHandler.GetCurrencyList();
}
else
{
return currencyTable;
}
}
Any help is appreciated, if there is a better way how to cache a DataTable please let me know.
Update:
Thanks to your opinions, this is the suggested method to do it, if I understood correctly:
public class BusinessLayerHandler
{
private static DataTable unitTable;
private static DataTable currencyTable;
private static readonly object unitTableLock = new object();
private static readonly object currencyTableLock = new object();
public static DataTable GetUnitList()
{
//import lists each time the application is run
//unitTable = null;
lock (unitTableLock)
{
if (unitTable == null)
{
return unitTable = DatabaseHandler.GetUnitList();
}
}
return unitTable;
}
public static DataTable GetCurrencyList()
{
//import lists each time the application is run
lock (currencyTableLock)
{
if (currencyTable == null)
{
return currencyTable = DatabaseHandler.GetCurrencyList();
}
}
return currencyTable;
}
}

It appears as though all you want to do is load it once and keep a reference to it. All you need to guard is initialising the variable if it's null. Null checking, locking and null checking again is called Double Check Locking and will work well for you. It's best practice to provide a separate locking object, so you have good control over granularity of locks.
Note this doesn't stop people from mutating the value inside the DataTable it only stops people from trying to initialise the static member at the same time.
private static readonly object UnitTableLock = new object();
private static DataTable unitTable;
private static bool _ready = false;
public static DataTable GetUnitList()
{
if (!_ready)
{
lock (UnitTableLock)
{
if (!_ready)
{
unitTable = new DataTable; //... etc
System.Threading.Thread.MemoryBarrier();
_ready = true;
}
}
}
return unitTable;
}
Only read from the result of GetUnitList never write to it.
Amended with reference to http://en.wikipedia.org/wiki/Double-checked_locking

I thought it would be worth adding that Double Check Locking has since been implemented in .net framework 4.0 in a class named Lazy. So if you would like your class to include the locking by default then you can use it like this:
public class MySingleton
{
private static readonly Lazy<MySingleton> _mySingleton = new Lazy<MySingleton>(() => new MySingleton());
private MySingleton() { }
public static MySingleton Instance
{
get
{
return _mySingleton.Value;
}
}
}

They are not thread safe. You should think about making your logic thread safe by your self, for example, by using lock operator.

If you are on .net 4 you could use ThreadLocal wrappers on your datatables

Static variables aren't thread safe per-se. You should design with thread safety in mind.
There's a good link to get you started: http://en.csharp-online.net/Singleton_design_pattern%3A_Thread-safe_Singleton
Apart from this, I would strongly recommend you to use a more modern approach than the legacy DataTable. Check out the Entity Framework or NHibernate. Implementing them in your datalayer will allow you to hide database details from the rest of the software and let it work on a higher level abstraction (POCO objects).

I think you should be fine. There is a liight chance that 2 threads will determine that the datatable is null and both read the table, but only one gets to assign the unitTable / currencyTable reference last, so worst case you be initalizing them more than once. But once they're set I think you'd be good. AS LONG AS YOU DON'T WRITE TO THEM. Theat could leave one in an inconsistent state.
If you want to avoid the double init you could wrap the whole getter code in a lock statement. It's a lot like initializing a singleton.
Also add a method that let's you set the references to null again so you can force a refresh.
GJ

If the DataTables are read-only then you should lock them when you populate them and if they never change then they will be thread safe.
public class BusinessLayerHandler
{
public static DataTable unitTable;
public static DataTable currencyTable;
private static readonly object unitTableLock = new object();
private static readonly object currencyTableLock = new object();
public static DataTable GetUnitList()
{
//import lists each time the application is run
lock(unitTableLock)
{
if (unitTable == null)
{
unitTable = DatabaseHandler.GetUnitList();
}
}
return unitTable;
}
public static DataTable GetCurrencyList()
{
//import lists each time the application is run
lock(currencyTableLock)
{
if (currencyTable == null)
{
currencyTable = DatabaseHandler.GetCurrencyList();
}
}
return currencyTable;
}
}
If you need really high performance on this lookup you can use the ReaderWriterLockSlim class instead of a full lock everytime to limit the number of waits that will happen in the application.
Check out http://kenegozi.com/blog/2010/08/15/readerwriterlockslim-vs-lock for a short article on the differences between lock and ReaderWriterLockSlim
EDIT: (Answer to comments below)
The unitTableLock object is used like a handle for the Monitor class in to synchronize against.
For a full overview of Theading and synchronization in the .NET framework I would point you over to this very extensive tutorial http://www.albahari.com/threading/

Related

C# lock to simultaneously read/write and display results

here's my question:
Say I have this program (I'll try to semplify as much as I can):
receiveResultThread waits for result from differents network clients, while displayResultToUIThread updates the UI with all the results received.
class Program
{
private static Tests TestHolder;
static void Main(string[] args)
{
TestHolder = new Tests();
Thread receiveResultsThread = new Thread(ReceiveResult);
receiveResultsThread.Start();
Thread displayResultToUIThread = new Thread(DisplayResults);
displayResultToUIThread.Start();
Console.ReadKey();
}
public static void ReceiveResult()
{
while (true)
{
if (IsNewTestResultReceivedFromNetwork())
{
lock (Tests.testLock)
TestHolder.ExecutedTests.Add(new Test { Result = "OK" });
}
Thread.Sleep(200);
}
}
private static void DisplayResults(object obj)
{
while (true)
{
lock (Tests.testLock)
{
DisplayAllResultInUIGrid(TestHolder.ExecutedTests);
}
Thread.Sleep(200);
}
}
}
class Test
{
public string Result { get; set; }
}
class Tests
{
public static readonly object testLock = new object();
public List<Test> ExecutedTests;
public Tests()
{
ExecutedTests = new List<Test>();
}
}
class UIManager
{
public static void DisplayAllResultInUIGrid(List<Test> list)
{
//Code to update UI.
}
}
Considering that the scope is to not update the UI while the other thread is adding tests to the list, it is safe to use:
lock (Tests.testLock)
or should I use:
lock (TestHolder.testLock)
(changing the static property of testLock)?
Do you think this is a good way to write this kind of program or can you suggest a better pattern?
Thank you for your help!
Public (not talking about public static) lock objects tend to be dangerous. Please see here
The reason it's bad practice to lock on a public object is that you can never be sure who ELSE is locking on that object.
Furthermore just having a List<T> and adding objects from an outer scope could be a smell, too.
In my opinion it'd be a better idea to have a method AddTest in Tests
class Tests
{
private static readonly object testLock = new object();
private List<Test> executedTests;
public Tests()
{
ExecutedTests = new List<Test>();
}
public void AddTest(Test t)
{
lock(testLock)
{
executedTests.Add(t);
}
}
public IEnumerable<Test> GetTests()
{
lock(testLock)
{
return executedTests.ToArray();
}
}
[...]
}
Clients of your tests class do not have to worry about using the lock object correctly. Precisely, they don't have to worry about any of the internals of your class.
You could, anyway, rename your class to ConcurrentTestsCollectionor the like, that users of the class know, that it's thread safe to some extent.
While you can use Tasks and the async/await keywords to do this less verbosely, I don't think it will fully solve your question.
I will assume that ExecutedTests is a List(or like) that you want to be thread safe, which is why you are creating a lock while accessing it.
I would make the list, itself, thread safe, rather than the operations against it. This will remove the need for a lock or a lock object.
You could implement this yourself or use something in the System.Collections.Concurrent namespace.
P.S.
If the threads are meant to be closed(aborted) when the process is exited you should set the Thread's IsBackground property to true.

Thread safe Singletion static method initialization

I'm implementing a singleton pattern, and need the initialization to be thread safe.
I've seen several ways to do it, like using the double check lock implementation, or other techniques (i.e.: http://csharpindepth.com/articles/general/singleton.aspx)
I wanted to know if the following approach, which is similar to the fourth version in the article, is thread safe. I'm basically calling a method in the static field initializer, which creates the instance. I don't care about the lazyness. Thanks!
public static class SharedTracerMock
{
private static Mock<ITracer> tracerMock = CreateTracerMock();
private static Mock<ITracer> CreateTracerMock()
{
tracerMock = new Mock<ITracer>();
return tracerMock;
}
public static Mock<ITracer> TracerMock
{
get
{
return tracerMock;
}
}
}
Yes, that's thread-safe - although it's not the normal singleton pattern, as there are no instances of your class itself. It's more of a "single-value factory pattern". The class will be initialized exactly once (assuming nothing calls the type initializer with reflection) and while it's being initialized in one thread, any other thread requesting TracerMock will have to wait.
Your code can also be simplified by removing the method though:
public static class SharedTracerMock
{
private static readonly Mock<ITracer> tracerMock = new Mock<ITracer>();
public static Mock<ITracer> TracerMock { get { return tracerMock; } }
}
Note that I've made the field readonly as well, which helps in terms of clarity. I generally stick trivial getters all on one line like this too, to avoid the bulk of lots of lines with just braces on (7 lines of code for one return statement feels like overkill).
In C# 6, this can be simplified even more using a readonly automatically implemented property:
public static class SharedTracerMock
{
public static Mock<ITracer> TracerMock { get; } = new Mock<ITracer>();
}
Of course, just because this property is thread-safe doesn't mean that the object it returns a reference to will be thread-safe... without knowing about Mock<T>, we can't really tell that.

Singleton in current thread

I have my singleton as below:
public class CurrentSingleton
{
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
{
lock (syncRoot)
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
}
}
return uniqueInstance;
}
}
I would like check, if I will have two thread, are there two different singletons? I think, I shall have two different singletons (with different references), so what I'm doing:
class Program
{
static void Main(string[] args)
{
int currentCounter = 0;
for (int i = 0; i < 100; i++)
{
cs1 = null;
cs2 = null;
Thread ct1 = new Thread(cfun1);
Thread ct2 = new Thread(cfun2);
ct1.Start();
ct2.Start();
if (cs1 == cs2) currentCounter++;
}
Console.WriteLine(currentCounter);
Console.Read();
}
static CurrentSingleton cs1;
static CurrentSingleton cs2;
static void cfun1()
{
cs1 = CurrentSingleton.getInstance();
}
static void cfun2()
{
cs2 = CurrentSingleton.getInstance();
}
}
I suppose that I should got currentCounter = 0 (in this case every two singleton are different - because are creating by other threrad). Unfortunately, I got for example currentCounter = 70 so in 70 cases I have the same singletons... Could you tell me why?
I would like check, if I will have two thread, are there two different singletons
No, there are not. A static field is shared across each entire AppDomain, not each thread.
If you want to have separate values per thread, I'd recommend using ThreadLocal<T> to store the backing data, as this will provide a nice wrapper for per-thread data.
Also, in C#, it's typically better to implement a lazy singleton via Lazy<T> instead of via double checked locking. This would look like:
public sealed class CurrentSingleton // Seal your singletons if possible
{
private static Lazy<CurrentSingleton> uniqueInstance = new Lazy<CurrentSingleton>(() => new CurrentSingleton());
private CurrentSingleton() { }
public static CurrentSingleton Instance // use a property, since this is C#...
{
get { return uniqueInstance.Value; }
}
}
To make a class that provides one instance per thread, you could use:
public sealed class InstancePerThread
{
private static ThreadLocal<InstancePerThread> instances = new ThreadLocal<InstancePerThread>(() => new InstancePerThread());
private InstancePerThread() {}
public static InstancePerThread Instance
{
get { return instances.Value; }
}
}
By default, a static field is a single instance shared by all threads that access it.
You should take a look at the [ThreadStatic] attribute. Apply it to a static field to make it have a distinct instance for each thread that accesses it.
Use of a locking object ensures that only one value gets created; you can verify this by putting some logging in your CurrentSingleton constructor.
However, I think there's a small gap in your logic: imagine that two threads simultaneously call this method, while uniqueInstance is null. Both will evaluate the = null clause, and advance to the locking. One will win, lock on syncRoot, and initialize uniqueInstance. When the lock block ends, the other will get its own lock, and initialize uniqueInstance again.
You need to lock on syncRoot before even testing whether uniqueInstance is null.
No matter what you do you are never going to get currentCounter = 0.
Because we are forgetting the the fact that application/C# code is also running in some thread and there are some priorities set by C# to run the code. If you debug the code by putting break points in Main method and CurrentSingleton you will notice that. By the time you reach and create the new Object for CurrentSingleton, for loop may be iteration 3 or 4 or any number. Iterations are fast and code is comparing null values and Object or Object and null value. And I think this is the catch.
Reed has got point static will always be shared hence you need to change your code in following way
public class CurrentSingleton
{
[ThreadStatic]
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
return uniqueInstance;
}
}
And as per analysis you are getting two different objects at 70th iteration but, that is something just mismatch may be null and Object or Object and null. To get successful two different object you need to use [ThreadStatic]

Is there a way to implement a lock free static configuration data?

public class MyConfigurationData
{
public double[] Data1 { get; set; }
public double[] Data2 { get; set; }
}
public class MyClass
{
private static object SyncObject = new object();
private static MyConfigurationData = null;
private static MyClass()
{
lock(SyncObject)
{
//Initialize Configuration Data
//This operation is bit slow as it needs to query the DB to retreive configuration data
}
}
public static MyMethodWhichNeedsConfigurationData()
{
lock(SyncObject)
{
//Multilple threads can call this method
//I lock only to an extent where I attempt to read the configuration data
}
}
}
In my application I need to create the configuration data only once and use it several multiple times. In other words, I write once and read many times. And also, I wanted to ensure that read should not happen till write operation is finished. In other words, I don't want to read MyConfigurationData as NULL.
What I know is the static constructor is called only once in an AppDomain. But, while I am preparing the configuration data, if any thread tries to read this data how would I ensure synchronization effectivey? In the end, I wanted to improve the performance of my read operation.
Can I implement my objective in a lock-free manner?
From MSDN:
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
So you don't need to use lock in your code, it is actually thread-safe. Your static constructor is called before MyMethodWhichNeedsConfigurationData is referenced.
public class MyClass
{
private static MyConfigurationData = null;
private static MyClass()
{
}
public static MyMethodWhichNeedsConfigurationData()
{
}
}
As long as you are only ever reading the data, it should already be thread-safe. Very few data-structures are not thread-safe when just reading (the obvious counter-examples might include lazy loading). Note that the static constructor is automatically synchronized by the runtime, so you don't need to concern yourself with multiple threads running the "Initialize Configuration Data" step.
So: as long as nothing ever mutates the data, you are already safe. You could also make it harder to get wrong by hiding the data behind an immutable interface, i.e.
public class ConfigurationData {
// or some similar immutable API...
public double GetData1(int index) { return data1[index]; }
public double GetData2(int index) { return data2[index]; }
private readonly double[] data1, data2;
public ConfigurationData(double[] data1, double[] data2) {
this.data1 = data1;
this.data2 = data2;
}
}
Then you don't need any locks:
public class MyClass
{
private static MyConfigurationData;
private static MyClass()
{
//Initialize Configuration Data
MyConfigurationData = ...
//This operation is bit slow as it needs to query the DB to retreive configuration data
}
public static MyMethodWhichNeedsConfigurationData()
{ //Multilple threads can call this method
var config = MyConfigurationData;
}
}
Note that removing the locks improves parallelism; it doesn't change raw single-threaded performance.
That said: I should advise against static data generally; it makes it very hard to test, and makes it tricky to do things like multi-tenancy if your needs change. It may be more prudent to have a single configuration instance, but pass it into the system as some form of context. Either approach can be used successfully, though - this is just something to be aware of.
I think you should use Singleton pattern and put your configuration initialization logic in "GetInstance" method which would return the instance of your class.
This way you would not need any locking mechanism for Read.

C# thread safety of global configuration settings

In a C# app, suppose I have a single global class that contains some configuration items, like so :
public class Options
{
int myConfigInt;
string myConfigString;
..etc.
}
static Options GlobalOptions;
the members of this class will be uses across different threads :
Thread1: GlobalOptions.myConfigString = blah;
while
Thread2: string thingie = GlobalOptions.myConfigString;
Using a lock for access to the GlobalOptions object would also unnecessary block when 2 threads are accessing different members, but on the other hand creating a sync-object for every member seems a bit over the top too.
Also, using a lock on the global options would make my code less nice I think;
if I have to write
string stringiwanttouse;
lock(GlobalOptions)
{
stringiwanttouse = GlobalOptions.myConfigString;
}
everywhere (and is this thread-safe or is stringiwanttouse now just a pointer to myConfigString ? Yeah, I'm new to C#....) instead of
string stringiwanttouse = GlobalOptions.myConfigString;
it makes the code look horrible.
So...
What is the best (and simplest!) way to ensure thread-safety ?
You could wrap the field in question (myConfigString in this case) in a Property, and have code in the Get/Set that uses either a Monitor.Lock or a Mutex. Then, accessing the property only locks that single field, and doesn't lock the whole class.
Edit: adding code
private static object obj = new object(); // only used for locking
public static string MyConfigString {
get {
lock(obj)
{
return myConfigstring;
}
}
set {
lock(obj)
{
myConfigstring = value;
}
}
}
The following was written before the OP's edit:
public static class Options
{
private static int _myConfigInt;
private static string _myConfigString;
private static bool _initialized = false;
private static object _locker = new object();
private static void InitializeIfNeeded()
{
if (!_initialized) {
lock (_locker) {
if (!_initialized) {
ReadConfiguration();
_initalized = true;
}
}
}
}
private static void ReadConfiguration() { // ... }
public static int MyConfigInt {
get {
InitializeIfNeeded();
return _myConfigInt;
}
}
public static string MyConfigString {
get {
InitializeIfNeeded();
return _myConfigstring;
}
}
//..etc.
}
After that edit, I can say that you should do something like the above, and only set configuration in one place - the configuration class. That way, it will be the only class modifying the configuration at runtime, and only when a configuration option is to be retrieved.
Your configurations may be 'global', but they should not be exposed as a global variable. If configurations don't change, they should be used to construct the objects that need the information - either manually or through a factory object. If they can change, then an object that watches the configuration file/database/whatever and implements the Observer pattern should be used.
Global variables (even those that happen to be a class instance) are a Bad Thing™
What do you mean by thread safety here? It's not the global object that needs to be thread safe, it is the accessing code. If two threads write to a member variable near the same instant, one of them will "win", but is that a problem? If your client code depends on the global value staying constant until it is done with some unit of processing, then you will need to create a synchronization object for each property that needs to be locked. There isn't any great way around that. You could just cache a local copy of the value to avoid problems, but the applicability of that fix will depend on your circumstances. Also, I wouldn't create a synch object for each property by default, but instead as you realize you will need it.

Categories

Resources