Hi, I have a Utility class with all static methods. By definition, static means only one instance.I m working on a multi-threaded application where I m using these static methods to do some work for me. I m making sure that I m not declaring and class level variables and restricting variables to the methods for thread safety. I m also making sure the object references are not available outside of the method. I m hoping this would make my variables created in these static methods not accessible from outside threads.
I don't quite understand how a static method with only one instance could handle multiple threads safely. I know all method variables are placed in a stack and each thread has its own stack. But, does it mean there are multiple instances of these methods or are they accessing the only instance of the method. I would appreciate your thoughts on this topic.
Static doesn't mean "one instance", it means "no instance". A static method is one that you can call without reference to an object (i.e., an instance of the class).
It sounds like you've got threads, static vs. instance methods, and multiple copies of code all mixed up in your head. Let me try to clear things up.
There is never more than one copy of the code for any method, whether it's static or an instance method. Multiple threads can simultaneously execute this one copy.
As you say, each thread has its own stack, and local variable in a method are allocated on that stack. That means if the method declares a local variable "x", and there are ten threads running that method simultaneously, then there are ten entirely separate "x" variables.
SO one copy of the code, and one copy of the local variables for each thread. Make sense?
Thanks Ernest for making it clear. That answers my question. I think that as long as all variables are local variables it doesn't matter whether the class is static or instance. They have their own stack trace and hence are thread safe.
Originally posted by Param Yanamandra: I think that as long as all variables are local variables it doesn't matter whether the class is static or instance. They have their own stack trace and hence are thread safe.
If the method refers to some global (shared) object using one of those variables, then of course you'd have a problem with interference between multiple threads; but as long as all the data the method uses is local to that method, then yes, you're correct.