During a test guys asked me a following question but my answer was wrong (not in my point of view). What is your opinion? Thank you in advance!
We have following thread safe implementation of the String Queue class. It is really thread safe, there is no catch in the class
public class StringQueue
{
private object _lockObject = new object();
private List<string> _items = new List<string>();
public bool IsEmpty()
{
lock (_lockObject)
return _items.Count == 0;
}
public void Enqueue(string item)
{
lock (_lockObject)
_items.Add(item);
}
public string Dequeue()
{
lock (_lockObject)
{
string result = _items[0];
_items.RemoveAt(0);
return result;
}
}
}
Problem of this class is that it throws exception on Dequeue operation, if the queue is empty. Therefore one software developer decided to add following function to the class, which returns null if the Queue is empty:
public string DequeueOrNull()
{
if (IsEmpty())
return null;
return Dequeue();
}
Is this function DequeueOrNull() thread safe?
My answer
Yes this function is safe. The function just calls two other safe functions and then it, for definition, is still safe. The explanation is, for new version of C#, when you check is the queue is empty and then you return null; C# jump the last return and then you don't received any errors. With old version of C# the last return is a problem and then you can fix it in this way:
public string DequeueOrNull()
{
if (IsEmpty())
return null;
else
return Dequeue();
}
"The function just calls two other safe functions and then it, for definition, is still safe."- By that definition all code is inherently "thread safe" because all code ultimately amounts to a series of atomic thread-safe operations. Your definition of thread safety is mistaken. - David