Is a readonly collection thread safe

  • Thread starter Thread starter David
  • Start date Start date
D

David

Hi guys

I have in my application many collections (HashTable and
ArrayList)loaded with configuration data, that means they are loaded
at startup and then they are accessed only for read-only (items are
only retrieved, never added, removed or replaced).
To be thread-safe after startup do I need to made them Synchronized
(and so slower), or are they thread safe in such case ?

Thanks in advance
David
 
Hi David,

I'd still recommend sticking to the safe way. As an alternative, introduce a
simple data holder class like this:

public class AppSettings
{
private int _setting1;
private string _setting2;

public AppSettings()
{
// Reads settings from some permanent storage and populates _setting1
and _setting2
}

public int Setting1
{
get
{
return _setting1;
}
}

public string Setting2
{
get
{
return _setting2;
}
}
}

and instantiate it on start-up and then safely access this data holder class
without any synchronization. You will most likely wish to turn this class
into a singleton - and that would be right decision - I have omitted any
singleton support for the sake of brevity.
 
MSDN:
"By default, Collections classes are generally not thread safe. Multiple
readers can safely read the collection; however, any modification to the
collection produces undefined results for all threads that access the
collection, including the reader threads."

So, as long as you only read the collections, it's ok. Generally the "thread
safety" is defined by the synchronization of threads when accessing a common
resource, producing/consuming in the same time, but as long as no one
modifies it it's ok.

Anyhow Hashtable is thread safe.
 
Back
Top