testing static member - thread safe?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

If many thread needs to test if one field of static class is null,

if (StaticClass.fieldA == null)

will it be thread safe and doesn't need thread synchronization?

Bob
 
If many thread needs to test if one field of static class is null,

if (StaticClass.fieldA == null)

will it be thread safe and doesn't need thread synchronization?

Only if fieldA is either readonly (and initialized as part of the
class initialization for StaticClass) or volatile.

Otherwise you could end up seeing "stale" values.

Jon
 
Jon Skeet said:
Only if fieldA is either readonly (and initialized as part of the
class initialization for StaticClass) or volatile.

Otherwise you could end up seeing "stale" values.

Jon

bbg:
... and you have to think about if old/stale values are a problem.

They usually are.

This goes further than just threading.
These are my idiom:

Always treat a property once.

int someCounter = myList.Count;
SomeClass.MyStaticMethod(someCounter);
for (int i; i < myList.Count; i++) // <- BAD, You called the property
twice.
{
// a property can do anything, even being recursive.
// it may or may not take time to complete.
// it may use DateTime or a GUID
// so try to take it into local scope once, and use it close.

// as what is not shown here, is that myList could be
// used by other threads, with maybe weird bugs as a result.
}

If you know you are using threads, you should lock before use.
I'd default to thinking nothing is thread-safe
unless the documentation promises me othervise.

But back to where I started.
Let's say I have a visit-counter on a webpage.
Let's say I 'cache' this number in StaticClass.fieldA.

Does it really matter if one user gets the correct 1234 users visited,
and other user gets 1233 stale count of users visited?
Will they call eachother up and ask about the difference?

I've done code where I knew I'd get stale answers,
but instead of using volatile, or locking, I was like Bond || Cartney;
- Live and let die.. or... live!

// Michael Starberg
 
Back
Top