Reputation: 375
I found a similar question to mine:
"Is class member function code memory allocated once or at every instantiation of objects? ", which can be found here
But the answer there only talked about the case for C/C++. Could anyone please tell me the answer to this question if I am using Java?
Upvotes: 3
Views: 1516
Reputation: 311023
Is class member function code memory allocated once or at every instantiation of objects
It is allocated once per class, not once per object. To be precise, it is allocated once per class/classloader pair. You can think of it as being allocated by the compiler, as long as you understand the compiler to include whatever the JIT or HotSpot does.
Upvotes: 2
Reputation: 5469
The answer is basically the same as in your other question, just that it is more dynamic. For the most popular Sun/Oracle VM: The executable code is compiled into the code cache on demand by the JIT (Just-In-Time) compiler and further optimized (e.g. inlined) on-the-fly by the Hotspot compiler.
When the method is called the method pointer, method variable references and values are placed on the stack as a context and then the code in the code cache is executed.
Upvotes: 1
Reputation: 3314
It's not a straightforward answer.
The code is loaded once when the class is loaded, but the code can be inlined into methods of other classes (and so loaded each time those other classes are loaded) and classes can be garbage collected and later re-loaded, so the code is loaded again.
Many aspects of the allocation will be dependent on the implementation of the VM, too.
Upvotes: 1