views:

660

answers:

5

I'm using static ArrayList in a class to store information about non-updatable database fields. I'm planing to initialize it in constructor once (init method call guarded by lock in constructor). After that multiple threads check if arraylist Contains a field. Do I have to control this read access in any way? For example by calling ArrayList.Synchronized.

+3  A: 

No, as long as you're reading you can just have at it.

ryber
thanks a lot for fast answer! think the keyword here was No, otherwise I didn't quite get the answer. it's good that I don't have to control the access since the application is quite time-critical.
matti
+3  A: 

No. Synchronisation is only required for stateful objects where your are going to change the state.

locster
+2  A: 

No (and you shouldnt need to when creating it either as long as you do it in the static constructor, which has an implicit multithread lock - if you're not in a position to do that, you probably will want to lock). There's a ReaderWriterLockSlim if you can use to control access if you do end up needing to to R/W access though.

Ruben Bartelink
"... and you shouldnt need to when creating it either..." - Not true, if creating it involves more than one machine language instruction cycle, and could be hit from multiple threads, then you do need to synchronize access to it. This is the canonical read-only singleton dilemma –
Charles Bretana
@Charles: Good point, have battened it down a bit (by saying that must be in a static constructor)
Ruben Bartelink
@Ruben, righto, static ctor is the way to eliminate the issue... removed my DV...
Charles Bretana
@Charles: cool - thanks. Good point though to pull people up on unguarded comments though. Do I see a +1 ?
Ruben Bartelink
thanks guys. it was before in static constructor without lock but i was not sure if it was a right way.
matti
+1  A: 

No, but consider wrapping it in a ReadOnlyCollection to make sure none of the threads can modify it.

Edit: However, to do this, you'd need to make the list a List<T> rather than an ArrayList.

R. Bemrose
A: 

For the initial creation of your List you could consider using a static constructor. This will only be called once on the first reference to the type.

TheZenker