PermGen space of heap - java

As shown in the image, Permgen is further divided into several parts.
Runtime constant pool stores constants pertaining to each type that is loaded by class loader.
Method area stores method information such as method return type, method name. (correct me if I am wrong here.)
And Reserved area is the part which is reserved if more memory is required by permgen.
But what I don't understand is, what is code area in the image? Any code is stored in this space(seems vague to me)?

Any code is stored in this space(seems vague to me)?
Any specific reason for that ?
The possible answer could be : Code area stores the byte code of the classes loaded into your memory.
But then the question comes, Why class is not loaded directly in RAM ?
Because we have a JVM to provide interoperability, Since JVM is an intermediary between java code and the machine , we need some place to store the code statements until JVM is scheduled by OS to execute its code.(for OS JVM is a process). So, It loads the byte code in Code area(if i am right) and when scheduled, further interprets code(.class) into underlying machine instructions.
The answer to me is "Code area holds the byte code of the classes".
To back the idea mentioned above ., here are some concepts copied as it is from Oracle blog which says:
So the Java classes are stored in the permanent generation. What all
does that entail? Besides the basic fields of a Java class there are:
Methods of a class (including the bytecodes)
Names of the classes (in the form of an object that points to a string also in the permanent generation)
Constant pool information (data read from the class file, see chapter 4 of the JVM specification for all the details).
Object arrays and type arrays associated with a class (e.g., an object array containing references to methods).
Internal objects created by the JVM (java/lang/Object or java/lang/exception for instance)
Information used for optimization by the compilers (JITs)
Hope it clears.

From an interesting article on the problems of PermGen: Will Java 8 Solve PermGen OutOfMemoryError?:
Jon Masamitsu, JVM developer at Oracle, explained 2006 in his blog the
purpose of the permanent generation: The permanent generation contains
information about classes, such as bytecode, names and JIT
information. It is stored in a separate space, because it is mostly
static and garbage collection can be much more optimized by separating
it.

Actually the PermGen store all your static code. i think this makes sense to you why there is a code area in PermGen.

I will venture to guess, based on the following article, by Jon Masamitsu, from which the following quote is taken, that the figure above is a misrepresentation (or rephrased - a misleading representation):
So the Java classes are stored in the permanent generation. What all
does that entail? Besides the basic fields of a Java class there are
Methods of a class (including the bytecodes)
Names of the classes (in
the form of an object that points to a string also in the permanent
generation)
Constant pool information (data read from the class file,
see chapter 4 of the JVM specification for all the details).
Object
arrays and type arrays associated with a class (e.g., an object array
containing references to methods).
Internal objects created by the JVM
(java/lang/Object or java/lang/exception for instance)
Information
used for optimization by the compilers (JITs)

The bytecode of all classes that have been resolved live in permgen. Just because a library has 1.2MB of classes doesn't they will be loaded by the JVM from the JAR. It it possible, even likely, that only a small fraction of those classes are used by a particular application.
You can run many large application servers whose sum total JAR size is >1GB using only 64MB permgen, because only a fraction of the classes are ever used.
Also take this example:
class A {
// ... code
}
class B {
void method1() {
// something
}
void method2() {
A a = new A();
}
}
While these classes may reside in the same JAR, merely creating an instance of B does not cause class A to be loaded. If you never call method2(), class A will never be loaded by the JVM. Additionally, contrary to popular belief, permgen can be garbage collected, and if space gets low, and there are no instances on the heap referring to class A anymore, then class A can be removed from permgen.

Related

Are there non-static and static areas in the method area of JVM memory?

I heard that there are non-static and static areas in JVM memory in a lecture course, but I can't find any information about the two areas of the method area of JVM memory.
Do non-static and static areas exist in the method area?
I think they must be because when the program needs some non-static method, JVM has to load the method on the non-static area of the method area and it has to be efficiently deleted if the non-static method is not used anymore by heap area or stack area.
I think you might be conflating storage requirements for methods (code) and fields (data).
Non-static fields are represented in the heap node of each object that has those fields. Naturally, when the object is deleted, all of its fields go away as well.
Static fields are represented in (typically) a heap node that is associated with the class that declares the fields. Normally, this node lives for the lifetime of the JVM. However, if the associated class is unloaded, then the node is (notionally) eligible for garbage collection.
Whether the former and latter nodes are in the same area of the heap is ... implementation-dependent.
I suspect that this is what the lecture was talking about. (However, it is not entirely clear without actually seeing/hearing what the lecture material says.
Are there non-static and static areas in the method area of JVM memory?
Basically, no.
The memory that holds the code of methods is associated with the class and has the same lifetime1 as the class (see above). Therefore the code for static and non-static (instance) methods can be (and is) stored the same way.
The area in which the code is stored is also implementation-dependent. However, for recent JVMs methods are held in metaspace ... which is not strictly part of the Java heap.
A final note: you don't need to know the precise details of this unless you are or plan to be an OpenJDK developer. And if you do need (or want) to know the precise details ... look at the source code. But beware that it could take you weeks to get your head around it, depending on how experienced you are with this kind of thing.
1 - This is an oversimplification. In some contexts, the JIT compiler may recompile native code. When that happens, the JVM will reallocate the memory blocks that hold a method's native code. However, it is all taken care of ...

How much space does a class take in the JVM?

I've been looking to no avail searching different sites because all the search results want to tell me how to compute the size of an object, not of a class.
When we define a class (with a .class file in a jar/war) and it gets loaded into the JVM, how much space does that take up? Obviously it depends on the actual things in the class, a class with more fields has more metadata to store. But if we say for example the class had 10 integer fields and 10 reference fields to other objects:
How much extra space would it take up in the JVM to have say, 1,000 of those classes (all extending the same base class)?
Would it change if they were anonymous classes instead of defined classes?
Well every Class itself is an object. So an indicative size would be to call Instrumentation.getObjectSize() on the class itself.
You can follow the tutorial here:
https://www.baeldung.com/java-size-of-object
And then if you want to check the size of MyClass you can do:
InstrumentationAgent.getObjectSize(MyClass.getClass());
This doesn't mean it is the only memory associated with this class, because the class loader, garbage collector and other internal workings of the JVM might keep other meta information about the class.
The answer will most definitely depend on JVM implementation (including version of such implementation, platform etc). There is no one number you can get.
As for anonymous inner classes, these still have class names generated for them, so this should have zero impact.

In Java, is there a way to track if a variable, a method or a class created in Heap or Stack?

I am trying to fully understand how the Java works with its memory arrangement. The discussions on Internet are very confused, and sometimes contradicts each other, so I found no one I can trust. This thing can be very complicate if it mixed with static, static method, local variable, thread, volatile and so on. So I am thinking if there is a way I can study that myself my doing some Java coding experiment. A class MemoryTrack does something like this,
public myMethod(){
int i = 0;
MemoryTrack.show(new myClass()); //print out "Heap at address 111"
MemoryTrack.show(new myClass()); //print out "Heap at address 222"
MemoryTrack.show(i); //print out "Stack at address 333"
MemoryTrack.show("a static method"); //print out "stack at address 444"
}
The use of memory is described in Section 2.5 of the Java Virtual Machine Specification. The stack stores stack frames (containing local variables and partial results). The heap is where all class instances and arrays come from. Stack frames can also be allocated from the heap (and then pushed onto the stack). There are also method areas and runtime constant pool memory. The details are spelled out in the spec.
As far as monitoring memory usage, several profilers have tools for that. For monitoring from within the program, take a look at the MemoryMXBean class (and related classes in the java.lang.management package). It's very easy to use. While it probably doesn't give you everything that it sounds like you want, but it's probably the best thing available.
The rule is pretty simple: heap contains objects, stack contains local variables and method parameters. Object fields are inside the objects, in the heap. Don't know about static fields. Methods and constructors are not stored in the stack, nor in the heap. Threads and volatile don't matter.
Method calls are on the stack. Each has a space reserved to it, the stack frame, that contains the local variables and the parameters.
Two things you need to know
its not as complicated as you think.
it doesn't matter 99% of the time.
Variables are always on the stack.
Objects are always on the heap. (There are exceptions but I wouldn't worry about them)
Methods and classes are always in the perm gen.
In the HotSpot/OpenJDK JVM, static fields are collected in a singleton object for the class. You can see the instance if you do a heap dump. Other JVMs may do this differently.
A class MemoryTrack does something like this,
Such a method wouldn't do anything useful as the argument will always be on the stack and object it refers to will always be on the heap. You can't get the memory location of an Object in a standard way and it unlikely to be useful if it did as it can change at any time.
You may think all variables in Java are on heap. Actually it is implementation dependent.

Java: Where is the memory allocated for the physical bytes of a class when loaded by a ClassLoader?

I have constructed a tiny custom class loader in a dummy application in order to understand how dynamic class loading works. For this question, I don't need to go into details about what it does other than to mention that it instantiates two different instances of my class loader and has each one load different classes, in order that I can satisfy myself by confirming a "ClassNotFoundException" from one of the class loader instances when only the other has loaded a particular class.
However, I have a question that can be easily expressed by the following, hopefully self-explanatory line of code.
Class clazz = myClassLoader.loadClass(theClazz);
This line of code causes my custom class loader to LOAD the class bytes into memory, and to return an instance of a Class object for that class.
My question is this: Where are the physical bytes of memory for the loaded class located (i.e., the contents of the .class file)? Are they stored inside the ClassLoader object, or are they stored inside the Class object (whereupon the ClassLoader object merely contains an internal reference to this Class object) - or somewhere else entirely?
The classloader object has a Collection of all classes it has loaded.
If the same physical class is loaded by 2 different class laoders, the bytes of that class are two times in memeory. The two classes behave like different types. They are not compatible to each other! Where the bytes are stored is not really relevant, I wonder why you want to know that. If you write your own ClassLoader you can "store" them where ever you want. However at some point you will make a call like: ClassLoader.defineClass(String, byte[], int, int). Then the relevant structures in memory inside the VM are created (MethodArea, ConstantPool etc.) as mentioned in other answers.
From the source code for ClassLoader:
// The classes loaded by this class loader. The only purpose of this table
// is to keep the classes from being GC'ed until the loader is GC'ed.
private Vector classes = new Vector();
The source code for the java classes are located in src.zip in your JDK directory.
Edit:
Was that what you asked about?
At the lowest level, the binary representation of the class is present in various runtime areas of the virtual machine, most notably in the Method Area and in the Runtime Constant Pool. In simpler terms, the Method Area is expected to contain information about the class, including the code for methods and constructors as evidenced by the following quote from the Virtual Machine Specification:
The Java virtual machine has a method
area that is shared among all Java
virtual machine threads. The method
area is analogous to the storage area
for compiled code of a conventional
language or analogous to the "text"
segment in a UNIX process. It stores
per-class structures such as the
runtime constant pool, field and
method data, and the code for methods
and constructors, including the
special methods (ยง3.9) used in class
and instance initialization and
interface type initialization.
"This line of code causes my custom class loader to LOAD the class bytes into memory, and to return an instance of a Class object for that class"
If I understand your question correct, memory allocation for objects is done on the heap space of the java process.
It depends on the JVM, seen for example here or here. Old versions of Mac OS used a pointer to pointer scheme, called a handle.
The class file and its internal, JVM-specific, representation are usually stored in the Permanent Generation - at least in the Sun/Oracle incarnation of the JVM.
See What does PermGen actually stand for? for more links.

What is perm space?

While learning about java memory profiling, I keep seeing the term "perm space" in addition to "heap." I know what the heap is - what's perm space?
It stands for permanent generation:
The permanent generation is special
because it holds meta-data describing
user classes (classes that are not
part of the Java language). Examples
of such meta-data are objects
describing classes and methods and
they are stored in the Permanent
Generation. Applications with large
code-base can quickly fill up this
segment of the heap which will cause
java.lang.OutOfMemoryError: PermGen no
matter how high your -Xmx and how much
memory you have on the machine.
Perm space is used to keep informations for loaded classes and few other advanced features like String Pool(for highly optimized string equality testing), which usually get created by String.intern() methods.
As your application(number of classes) will grow this space shall get filled quickly, since the garbage collection on this Space is not much effective to clean up as required, you quickly get Out of Memory : perm gen space error. After then, no application shall run on that machine effectively even after having a huge empty JVM.
Before starting your application you should java -XX:MaxPermSize to get rid of this error.
Simple (and oversimplified) answer: it's where the jvm stores its own bookkeeping data, as opposed to your data.
Perm Gen stands for permanent generation which holds the meta-data information about the classes.
Suppose if you create a class name A, it's instance variable will be stored in heap memory and class A along with static classloaders will be stored in permanent generation.
Garbage collectors will find it difficult to clear or free the memory space stored in permanent generation memory. Hence it is always recommended to keep the permgen memory settings to the advisable limit.
JAVA8 has introduced the concept called meta-space generation, hence permgen is no longer needed when you use jdk 1.8 versions.
The permgen space is the area of heap that holds all the reflective data of the virtual machine itself, such as class and method objects.
It holds stuff like class definitions, string pool, etc. I guess you could call it meta-data.
Permgen space is always known as method area.When the classloader subsystem will load the the class file(byte code) to the method area(permGen).
It contains all the class metadata eg: Fully qualified name of your class, Fully qualified name of the immediate parent class, variable info, constructor info, constant pool infor etc.
What exists under PremGen : Class Area comes under PremGen area. Static fields are also developed at class loading time, so they also exist in PremGen. Constant Pool area having all immutable fields that are pooled like String are kept here. In addition to that, class data loaded by class loaders, Object arrays, internal objects used by jvm are also located.
PermGen Space stands for memory allocation for Permanent generation All Java immutable objects come under this category, like String which is created with literals or with String.intern() methods and for loading the classes into memory. PermGen Space speeds up our String equality searching.
JVM has an internal representation of Java objects and those internal representations
are stored in the heap (in the young generation or the tenured generation).
JVM also has an internal representation of the Java classes and those
are stored in the permanent generation

Categories