I read some articles and did some testings/investigating and I think there's NOT accurate conculsion (due to incorrect wording maybe )
Ok . few investigations :
There was this guy who asked this question :
Why are static fields generally considered threadsafe?
Well , all of the repliers said : No. they are not.
Eric also said :
You have it backwards.Because static fields and methods are likely to be accessed from multiple threads, it is a good programming practice to do the work to ensure that they are threadsafe.
(this is pretty close to my claim which i'll ask here later)
But I also found here that Hans said :
And oh boy — this other guy said :
Re-entrancy is still a problem, though. static is not thread-safe, and even static readonly is not re-entrant-safe.
Ok , i'm confused.
p.s. I'm not talking about this kind of situation :
public class A
{
public static List<int> LST = new List<int>();
}
List<>
is not thread safe so I don't care who holds it. BUT ->
Let's look at this
public class A
{
public static int Five=5;
}
What is not thread safe about this code ?
I can't see how Five
could not always be 5 :
As far as I know - Five
could never be 0
( initial value) and it would always be five no matter how many threads are accessing it !
NOW , I DO AGREE that If I was writing a code which USES this Five
field , then I'd have to watch out for changed value !
Example :
if (Five < array.Length) return array[five]; //can throw an IndexOutOfBoundsException if five is modified
With this - I Agree !
But (imho) it is incorrect to say ( as a rule) that static fields are not thread safe !
Their usage has to be treated as if it could change via another thread.
(Also, obviously - Static fields which reference a non-threadsafe object like List<>
- surely not going to be thread safe)
What i'm trying to say here is that static fields are not thread safe for specific scenarios , and not as a rule !
Question :
Can someone please shed light ? I'm sure I miss something here ( or am I not ? ) is it true that static fields are not always non-thread safe ( as a rule)
And what about this
readonly
which makes static field threadsafe (all it does it make it one time initialize without reassigned ) ? does it make it thread safe or does it not ? (and what about re-entrent ?)