views:

52

answers:

3

hi

I was told that in multithread programs, we would have some troubles by static classes.

Could you please explain it more ?

+2  A: 

If static classes has any static state (e.g., "global" variables), it is shared across all threads. If the programmer isn't careful, there will be problems interacting with these classes. There's more but this is the gist of it.

Jeff M
+2  A: 

Statics & Thread Safety
http://odetocode.com/Articles/313.aspx

Robert Harvey
A: 

With multithreaded programs you could have some trouble with anything, not just static classes. When dealing with multithreading, the main concern is usually with data-contention... in other words: ensuring proper operation when reading-from or writing-to a shared resource. Static classes there have some challenges, but there also have some potential benefits:

Challenge

  • By default some data is exposed, directly as a member variable or indirectly through an accessor/mutator, so protecting the resource is more challenging.
  • Anybody that's using the static class could cause problems with multithreading if they use the proper synchronization.

Benefit

A potential benefit is that if the static data is constant, then there will be no need for synchronization since the data can only be read not written to. A popular example is a Singleton class that uses a static instance and the instance gets initialized only once, so there is no need to synchronize for the Singleton instance. There still may be a need for synchronization on the data contained within the

Singleton

instance

Lirik