Will the JVM allocate 10 different memory spaces for 10 instances during the creation of the object (I mean at the time when I call the constructor, i.e. the new MyClass ();
This can be done, however, by using escape analysis, it can push them onto the stack or completely eliminate them.
or will it load the class definition once in memory and each instance when calling each of these 10 methods at runtime, will the JVM allocate memory?
If you have one ClassLoader, you will get one instance of the class, however, if each instance has its own ClassLoader, you will get a copy of the class in each ClassLoader. Note: each ClassLoader may have a different version of the class with the same name.
To eliminate some misunderstandings, my question is to create an object, I know that all data members are allocated in the memory heap,
Class and method information (including byte code) stored on the heap in PermGen (Java <7) or metaspace (Java 8 +)
The actual instance is usually added to the heap, but not necessarily.
I'm not sure if methods that have not yet been called are allocated differently in memory for each object or not?
The JVM goes through many stages of optimization, and when you call a method, it can optimize it, inline, or even eliminate it. You can see that the methods are compiled (and even re-optimized) by adding -XX:+PrintCompilation on the command line.
Peter Lawrey
source share