I had read this question
Static method behavior in multi-threaded environment in java.
But this question didn't answer that can multi-thread running the same method at the same given time in a multicore processor enviroment.
If my title question is "yes", how exactly does my computer implement this? Since there is only one static method waiting to be called.
Do two cores respectively copy that static method to their ram of core and run them simultaneously and respectively?
I don't know if I express my point clearly. If not, I am more than willing to explain it. Thank you.
All of the information required to execute a piece of code independently is stored locally in a thread. When a core executes a method it does so in the context of a thread. Since the actual executable code (the instructions) cannot be changed (it is not writeable), there is no need to copy it anywhere: it can just be shared between threads/cores.
Methods can have local variables. These are stored on the stack, which is a property of the thread. Each thread has a separate piece of memory for its stack, and so each core will be accessing different memory for local variables.
For data on the heap, this is shared, which is why you have to take care when accessing that in a multi-threaded environment by co-ordinating access (for example, by using synchronized
).
Being static or not static is not relevant. In either case, there is only one copy of the code. A non-static method can have multiple instances of the object data (and so potentially different cores will be accessing different heap data, although not necessarily) and a static method accesses static data (which is shared, and you have to co-ordinate that).
A core may copy executable code to a local cache for execution, but this is done for performance reasons and not because of any issues with shareability.
Quick answer: yes.