views:

52

answers:

4

Consider the scenario below:

  • The application is multi-threaded and it has one static ArrayList used globally.
  • The application has one thread that reconstruct the ArrayList entirely from data read from database from time to time.
  • The application has N threads reading from this global ArrayList in parallel.

What is the best approach to thread-safe the multiple parallel reads and the occasional altering of the ArrayList object?

+1  A: 

I would look at using ReaderWriterLockSlim for that: http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

CarlosAg
No "slim" if he's still stuck on 2.0
Hans Passant
A: 

Could you not simply make the Arraylist a static property of a class? Then provide get; set; accessors which wrap "lock(object objMutex) {...}" around the Arraylist object? This would then ensure that there was only synchronous access to the object across all threads.

Brian Scott
A: 

If it contains a cache of readonly data read from a database and is never modified, you probably don't need any synchronisation.

You do of course need to construct the list completely before setting the global reference, e.g.:

private static ArrayList myList;

...
myList = GetListFromDatabase();

In the event of a race condition when a writer thread replaces the list, another thread can get the "old" copy of the list, but if it's not being modified this old copy will still be consistent.

Joe
Good! It is simple and it works. The only inconvenience is that while the ArrayList is being reconstructed, the cache takes 2x memory because the "main" ArrayList is not removed, but the GC collects the ArrayList after referencing to the new object.
LrycXC
A: 

Also you can look to the System.Collections.Concurrent (if you use .NET 4.0) This collections is optimised for multithreading. Good article about this container is .NET 4.0 and System.Collections.Concurrent.ConcurrentBag

Andrew