简体   繁体   中英

How the memory is allocated for class member functions in Java

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?

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.

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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM