This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Easily. A method is just a set of instructions. If I give the same set of instructions to 100 people (or 100 threads), they're all following that same set of instructions, concurrently. The fact that they all their instructions are the same doesn't prevent them from executing those instructions at the same time. Not by default, anyway.
The problem is the data. Does the data being used change over time? Do the different people / threads change the data themselves? Are different people / threads changing the same data, simultaneously? Or is each person or thread using a different set of data? If they're using different data, that's no problem. But if they are sharing data, and changing it, you probably need to set up some rules to ensure that they don't interfere with each other too much. For Java threads, this usually means using synchronization, or java.util.concurrent locks. That's a longer discussion - but if you are using synchronization or locks, that means you are setting up something that can prevent two different threads from executing code to alter the same data at the same time. So, if you have done this, that may prevent two different threads from executing the same method at the same time. But if you haven't done this (hopefully, because there was no need to do this), then nothing prevents multiple threads executing the same method at the same time.
Joined: Feb 02, 2005
Thanks for your explanation Mike...
If assuming my static function has no shared data between threads, what then is the advantage of using static method vs instance method?
My understanding is that only one copy of each method is loaded. The state
of each object's method call (parameters and local variables) is saved on the
stack. The currently executing thread operates on its own state using the
shared method logic. Static methods are no different than instance methods.
They are just restricted to operating on static variables, those available to all
instances of the class.