How to manage memory when loading classes in Java?

Imagine that I have a class with 10 methods, and I need to create 10 objects from the class. The question arises: Will the JVM allocate 10 different memory spaces for 10 instances during object creation (I mean at the time I call the constructor, i.e. the new MyClass () ;? , or will it load the class definition one once in memory and each instance when calling each of these 10 methods at run time does the JVM allocate memory?

To eliminate some misunderstandings, my question is to create an object, I know that all data members are allocated in heap memory, but I'm not sure if methods that have not yet been called are allocated differently in memory for each object or not?

+7
java jvm
source share
3 answers

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.

+3
source share

Yes. Class metadata is loaded into Permgen space (MetaSpace in Java8). So, as soon as the class is loaded, all methods (static and non-static) are available. Methods that were not called will also be loaded as part of this metadata. All methods will be loaded only once.

+2
source share

While the class is loading, all methods of the class (both static and non-static) are also loaded into memory. It does not matter how many of them load.

For each object, the JVM will allocate a different memory location.

Let's pretend that

 MyClass m1 = new MyClass(); // one memory location MyClass m2 = new MyClass(); // different location MyClass m3 = m1; // same memory location of m1 object 
-one
source share

All Articles