When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about calling the class with locking I am meaning I am working for Microsoft create XXX class\object and I want to be say it is "Thread Safe" what would I need to do?
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
By creating a queue of tasks where only one task can be processed at any given time, you are indirectly introducing thread safety to the component that is using the queue.
The easiest and most foolproof way of making a class thread safe is to make it immutable. The beauty of it is that you don't ever have to bother with locking again.
Recipe: Make all instance variables readonly
in C# (final
in Java).
See this question as well.
In addition to the other excellent answers here, consider another angle as well.
It isn't enough that the internal data structure of the class is 100% thread safe if the public API has multi-step operations that cannot be used in a thread-safe manner.
Consider a list class that has been built such that no matter how many threads are doing no matter how many types of operations on it, the internal data structure of the list will always be consistent and OK.
Consider this code:
if (list.Count > 0)
{
var item = list[0];
}
The problem here is that between the reading of the Count
property and the reading of the first element through the [0]
indexer, another thread might have cleared out the contents of the list.
This type of thread safety is usually forgotten when the public API is created. Here, the only solution is for the calling code to manually lock on something on each such type of access to prevent the code from crashing.
One way to solve this would be for the list type author to consider typical usage scenarios and add the appropriate methods to the type:
public bool TryGetFirstElement(out T element)
then you would have:
T element;
if (list.TryGetFirstElement(out element))
{
....
presumably, TryGetFirstElement
works in a thread-safe manner, and would never return true
at the same time as it is not able to read the first element value.
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