Originally posted by O. Ziggy:
Hi all,
I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time.
Be careful here -- you're inventing things. There's but a single copy of the code for
all methods, static or not; and there's absolutely no problem in having any number of threads call a given method at once. The difference between a static and non-static method is that a non-static (or "instance") method has the "this" keyword available to refer to a "current object", while in a static method, there is no current object at all.
Where there can be problems is if multiple threads execute code that affects a single object -- or more properly, a single
variable -- at the same time.
My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA are executed at the same time? Woulnt the static method in ClassB corrupt the data?
The static method only operates on data that is passed in as arguments; there is no data that would be shared by all calls to this method. Therefore, it can be called by any number of threads at the same time, as long as each
thread passes in its own data. Note that this really has nothing to do with the method being static or not.