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?
source to share
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.
source to share
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
source to share