We have two classifications heap and stack . When a object is created, memory for object is stored in heap. What if the class has static methods ,which can be called using class name. If object is not created then how will it allocate memory and if it does where will it allocate memory?
It depends on the JVM, but static fields are usually stored in a special object on the heap. (You can see it in a heap dump) When the ClassLoader is unloaded, its classes and their static "objects"/fields are also cleaned up.
The only thing different about the static "object" is you can't get a reference to it. (But you can use reflection to access the fields)
Methods (i.e., code) aren't stored in an object; all objects of a class will share the code for a method. Regardless of language (Java, C++, or virtually anything else) there will be only a single copy of the code for any method, static or not. Generally there's a specific area of memory -- i.e., a CODE segment in a native language like C++, or a special heap area in Java -- where code is loaded.
Permanent Generation(PermGen) space of heap contain permanent class
metadata and descriptors information.
PermGen space always reserved for classes and those that are tied to
the classes(Static members, static functions, etc...)
Static function belongs to the class so they can be called to without
creating the object of the class.
Related
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 ...
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.
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.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
static allocation in java - heap, stack and permanent generation
its a small confusion...defining static to class, methods and variables.In this three cases where thus the memory allocated. ? My boss is familiar with C,he says only variables are in heap memory and rest (static classes and static methods) will remain in main memory. is that ture? any explanation.?
one more
in android using static class and static methods is a best practice ?
Try this,
static members are stored in Method Area.
Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.
Non-heap Memory
It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.
Method Area
As given in the last line, method area is part of non-heap memory( A special heap area). It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.
The above three (heap memory, non-heap memory and method area) are the main jargon when it comes to memory and JVM.
Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.
Static variables are saved in the same place as the Classes declaration (methods and attributes, etc). 1). Classes (loaded by the classloaders) go in a special area on heap called Permanent Generation, and static field too go to the same place as they are common to each instance of the class.
For more details :
see this answer
This is a follow-up question to How are static arrays stored in Java memory? .
So global variables in C/C++ are stored in the static data segment of memory. But what about static class variables in Java/C++?
It can't be the static data segment because you don't know what/how many classes are going to be referenced throughout the duration of your program (because of reflection). It's definitely not the stack because that makes no sense. Storing it on the heap is also kind of iffy.
In Java, at a low level, class static variables are indeed stored on the heap, along with all other class metadata. To Java, they look like globals, but to the JVM's low level heap management routines, they're dynamic data (although they may be treated slightly specially in order to improve GC efficiency, since they're likely to be long lived). After all, classes can be unloaded by unreferencing their classloader.
As for whether it's the same as the C malloc(), not likely. Most JVMs take control of their heaps at a low level; they grab a chunk of memory from the OS and divvy it up themselves. As such, most Java data, including static data, are not stored in the malloc heap, but rather in a separate heap managed by the JVM.
Java has a "permanent" heap where it puts class metadata. So the "roots" of the static values are in the permanent heap. The values are reference values (class objects) the values themselves are in the regular heap.
Static variables will not be stored in Heap.. They are part of Data Segment.
Local variables will be stored in - Stack;
Instance variables will be stored in - Heap;
Class variables(Static) will be stored in - Data Segment. These variables will be shared across all objects of that class..
Your final machine equivalent java code will be stored in - Code/text segment.