How to manage memory when loading classes in Java?
Imagine that I have a class with 10 methods, and I need to instantiate 10 objects from the class
In order to clear up some misunderstandings, my problem is that when creating objects, I know that all data members are allocated in heap memory, but I'm not sure whether the methods that have not been called allocate different or not for each object in memory?
Solution
It may, but with escape analysis, it can put them on the stack or eliminate them altogether
If you have a classloader, you will get an instance of the class, but if each instance has its own classloader, you will get a copy of the class in each classloader Note: each classloader can have different versions of classes with the same name
The actual instances of class and method information (including byte code) stored in the heap in permgen (Java < 7) or Metaspace (Java 8) are nominally added to the heap, but not necessarily
The JVM goes through many optimization stages. When you call a method, it may optimize it, inline it, or even eliminate it You can view the methods being compiled (or even re optimized) by adding - XX: printcompilation on the command line