Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is memory managed while loading classes in Java?

Tags:

java

jvm

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?

like image 966
Morteza Naeimabadi Avatar asked May 27 '15 06:05

Morteza Naeimabadi


2 Answers

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.

like image 158
Peter Lawrey Avatar answered Oct 20 '22 07:10

Peter Lawrey


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.

like image 35
TheLostMind Avatar answered Oct 20 '22 06:10

TheLostMind