Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a unit test for thread unsafe collection

I'm writing a doubly-linked list using TDD approach. This collection type is not thread safe. In order to implement the ICollection interface my list class must have several public properties (including IsSynchronized and SyncRoot which are used to provide a thread-safe way for collection using). The code of these two properties is pretty simple:

public bool IsSynchronized { get { return false; } }

private readonly object _syncRoot = new object();
public object SyncRoot { get { return _syncRoot; } }

The question is how to write a correct unit test for it. This test should check the right usage and incorrect usage either.

like image 270
Igor Soloydenko Avatar asked Oct 15 '25 14:10

Igor Soloydenko


1 Answers

my list class must have several public properties (including IsSynchronized and SyncRoot

It doesn't. This dates back to .NET version 1 and is widely considered a giant mistake. It created a false sense of thread-safety that got a lot of programmers in deep trouble. Such a class wasn't actually thread-safe in all cases, iterating for one wasn't. It was completely dropped in the .NET 2.0 generic collection classes. And you should not implement ICollection, a modern collection class should be generic and implement ICollection<T>. That unfortunately still requires implementing IEnumerable, a legacy we'll probably never get rid of. You implement it with an explicit implementation, such methods are not public.

A secondary consideration is whether implementing ICollection<> is a good idea. A linked list makes a member like Count expensive, it is O(n) by nature. You need to track the number of elements in the list separately to make it O(1). The .NET LinkedList<> class, also a doubly linked-list collection class, does do this.

like image 135
Hans Passant Avatar answered Oct 17 '25 04:10

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!