How is memory managed while loading classes in Java?

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 ie 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 ie 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.


While class is loading, all the methods of the class (both static and non-static) also loading into the memory. No Matter how many are there all are loading.

For every object JVM will allocate different memory location.

Suppose

MyClass m1 = new MyClass(); // one memory location

MyClass m2 = new MyClass(); // different location

MyClass m3 = m1; // same memory location of m1 object
链接地址: http://www.djcxy.com/p/85504.html

上一篇: 停止EditText在Activity启动时获得焦点

下一篇: 在Java中加载类时如何管理内存?