Method definition and objects in Java

58 Views Asked by At

Do class objects in Java have their own copy of methods or is it limited to the class definition. If the latter is true then how do objects, in a mult-threaded environment gets access to the method instructions.

Wanted to know how method calls work in mult-threaded environment if the same method is being called for the objects of the same class.

Tried searching on Google, chatgpt etc. but couldn't get an accurate answer on this works.

1

There are 1 best solutions below

0
Joseph Larson On

Interesting question. Computer memory within a single running program is one big pool. And all your code resides within a single copy. No, your individual threads do not get their own copies. For that matter, they don't get their own copies of your data, either, unless you create new objects within the thread and don't let anyone else have them.

It's safe, though, because the code is static and isn't going to get modified. Variables your methods use will be unique and safe, though. So if you do this:

public void foo() {
    int value = 10;
}

Then everyone running foo will have their own version of value. For that matter, if foo recurses (calls itself), then you now have two copies of value -- one in the first invocation and a different one in the second.