Say we have a class that is frequently used in a single-thread context:
public class Foo
{
public List<Bar> Data;
public virtual void ChangeData()
{
for(var i =0; i < Data.Count; i++)
{
if(i % 4 == 0)
{
data[i].Baz();
}
}
}
}
If we were to decide we wanted to use the thread in a multi-threaded context (in addition to its current single-threaded usage), are there advantages (assuming it has full unit test coverage) to making a thread-safe subclass ‘ThreadSafeFoo’ vs. altering ‘Foo’ to be thread safe?
I was wondering about this because there are specific subclasses in System.Collections
that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn’t simply rolled into List
, etc.
I was wondering about this because there are specific subclasses in System.Collections that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn’t simply rolled into List, etc.
In this specific example, it is because only a very limited subset of actions on say… Dictionary
can be done performantly in ConcurrentDictionary
. Subjecting all of your users to the overhead of synchronization (or the functionality limitations) is… not advised.
In the more general case, you should generally err towards using only one class. It reduces the complexity of your code. It is less code to maintain. It makes it easier for people to do “the right thing”. Sometimes it’s too onerous to provide the thread safety, and you get two classes. But if it’s not, or it’s close – just use the one.
The problem with this kind of thinking is that you often can’t just make a class thread-safe (at least not in a way that is useful), without also modifying how it works. And collections demonstrate this nicely: for example, using normal Dictionary
, you could implement some kind of caching like this:
if (!dictionary.ContainsKey(key))
dictionary.Add(key, GetValue(key));
return dictionary[key];
But such code wouldn’t work well in a multi-threaded environment, even if there was a version of Dictionary
with ContainsKey()
, Add()
and the indexer that are thread-safe.
Instead, using ConcurrentDictionary
(with is not a subclass of Dictionary
), you could write the same code like this:
return dictionary.GetOrAdd(key, GetValue);
But you usually don’t need to go that far to achieve thread-safety, the right way of using a lock
is enough:
lock (dictionary)
{
if (!dictionary.ContainsKey(key))
dictionary.Add(key, GetValue(key));
return dictionary[key];
}
But this means using the type in a thread-safe way, not changing it or creating a subclass.