Posts Tagged ArrayList
Revealing synchronization magic of ArayList.Synchronized collection
Today I looked (and still looking) for some kind of synchronized non blocking container. When I saying “non blocking”, I mean while threads are waiting to take access over a container, they continue to do their work – performance improvement (on multi processors machine only, of cause).
I always prefer to find some existing, working and well tested solution, instead of reinventing wheel. One my colleague suggested to use ArrayList.Synchronized method, which is creates synchronized collection from requested type (ArrayList or any other collection implementing IList interface). He claimed that synchronization of ArrayList.Synchronized collection is implemented better than an ordinary lock, and its performance is better as well. I decided to test this collection, and used Reflector to dig inside it.
After locating Synchronized method inside the ArrayList class, I noticed that actually SyncArrayList wrapper created around provided collection (ArrayList ot IList), and looks as the following:
public static ArrayList Synchronized(ArrayList list)
{
if (list == null)
{
throw new ArgumentNullException(“list”);
}
return new SyncArrayList(list);
}
Ok, now the question is: how Add method implemented inside SyncArrayList? Here is the answer:
public override int Add(object value)
{
lock (this._root)
{
return this._list.Add(value);
}
}
SyncArrayList actually using the same lock we all know! Therefore, there is nothing special about ArrayList.Synchronized synchronization, performance is exactly the same. Moreover, if you have to add 200 items to your synchronized collection, you going to lock and unlock it 200 times! On the other hand, if you are the one who controlling synchronization (manually locking) – then you will lock and unlock only once – just before and after adding all the 200 items.
From the all stated above, the conclusion is obvious: use ArrayList.Synchronized collection only when you want to guarantee its synchronization, even by cost of performance.
P.S. As I said, I still looking solution to my problem. I will appreciate any help on this.
Add comment February 14, 2008