Imagine I've got a class with 10 methods and I need to instantiate 10 objects from the class. The question is: Will JVM allocate 10 different memory spaces for 10 instances at object creation time (I mean at the time I call the constructor i.e. new MyClass(); ? or it will load the class definition once in memory and each instance while calling each of those 10 methods, at run time, JVM will allocate the memory?
To clear some misunderstanding, my question is when creating an object, I know that all data members are allocated in heap memory, but I'm not sure whether the methods which hasn't been yet called are allocated differently in memory for each object or not?
Will JVM allocate 10 different memory spaces for 10 instances at object creation time (I mean at the time I call the constructor i.e. new MyClass();
It might do, however with escape analysis, it can place them on the stack or eliminate them entirely.
or it will load the class definition once in memory and each instance while calling each of those 10 methods, at run time, JVM will allocate the memory?
If you have one ClassLoader you will get one instance of the class, however if each instance has it's own ClassLoader, you will get a copy of the class in each ClassLoader. Note: each ClassLoader could have a different version of the class with the same name.
To clear some misunderstanding, my question is when creating an object, I know that all data members are allocated in heap memory,
The class and method information (including byte code) it stored off the heap in the PermGen (Java <7) or MetaSpace (Java 8+)
The actual instance is notionally added to the heap, but doesn't have to be.
I'm not sure whether the methods which hasn't been yet called are allocated differently in memory for each object or not?
The JVM goes through many stages of optimisation and when you call a method it might optimise it, inline it or even eliminate it. You can see methods being compiled (and even re-optimised) by adding -XX:+PrintCompilation
on the command line.
Yes. Class Metadata is loaded into Permgen space (MetaSpace in Java8). So, once the class is loaded, all methods are available (static and non-static). Methods which haven't been called will also be loaded as part of this metadata. All methods will be loaded only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With