Immutability and static variables

I am developing some immutable classes, but I have some variables like say .Count

to have the total number of instances. But will a static variable affect multithreading?

Because methods like Add, Remove, etc. need to update the value .Count

. Maybe I should make this a lazy property?

+1


source to share


4 answers


If you are just doing a counter, blocked operations can be an option, not a blocking. MSDN has a good example of this in the context of reference counting.



+2


source


You might want to consider the functions from the Interlocked class, at least in the example you provided.



+2


source


But will a static variable affect multithreading?

exactly! the shared state is influenced, by refutation, by multithreading.

Because methods like Add, Remove, etc. have to update the .Count value. Maybe I should make this a lazy property?

it's better to use a class that does atomic add (like AtomicInteger in java) to avoid blocking: look here

+1


source


Yes, whenever you update a shared variable in a multithreaded environment, you just need to wrap those updates in a lock.

0


source







All Articles