Is a readonly collection thread safe

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
 
D

Dmitriy Lapshin [C# / .NET MVP]

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.
 
H

Horatiu Ripa

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top