I don't have much idea on Java.
I was going through few links and found blog says "Java Primitives stored on stack", which I feel it depends on instance variable or local variable.
After going through several links my conclusion is,
Class variables – primitives – are stored on heap as a part of Object which it contains.
Class variables – object(User Defined) – are stored on heap as a part of Object which it contains. This is true for both reference and actual object.
Method Variables – Primitives – are stored on stack as a part of that stack frame.
Method Variables – object(User Defined) – are stored on heap but a reference to that area on heap is stored on stack as a part of that stack frame.
References can also be get stored on heap if Object contains another object in it.
Static methods (in fact all methods) as well as static variables are stored in heap.
Please correct me if my understanding is wrong. Thanks.
There are some optimizations in the JVM that may even use the Stack for Objects, this reduces the garbage collection effort.
Classes are stored on a special part of the heap, but that depends on the JVM you use. (Permgen f.e. in Hotspot <= 24).
In general you should not have to think about where the data is stored, but more about the semantics like visibility and how long something lives. Your explanation in the questions looks good so far.
"Method Variables – object(User Defined) – are stored on heap but ..."
Wrong.
First, method variables are called local variables.
Let's consider
public static void main(String[] args) {
List<Integer> model = new ArrayList<Integer>();
Variable model is placed in the stack frame, not on heap. The referenced object generated with new ArrayList<Integer>() is placed in the heap but it is not a local variable.
The 3 things:
variable model
generated object
reference to that object, stored in a variable
are quite different, do not mess them up.
Object are stored in the Heap.
The object reference stored in the stack.
Static variable stored in the method area.
Example
abc obj=new abc();
abc object save in the heap and the object reference is stored in the stack.
static int i=10;
i variable stored in the method area.
Related
I have not been able to find any reliable literature on this but i'm curious as to where an object is stored if its created inside of a method ? on the stack or on the heap in java 8?
public class A {}
.
.
.
public class B {
public void test(){
A m = new A();
}
}
I know that normally only local primitives, reference variables and function calls are stored on the stack and that objects are stored in the heap
So I'm assuming that one of the following two scenarios is true either
Case 1 : Objects instantiated in a method are as usual stored in the heap with a reference to that object in the stack then when the function finishes the object reference goes out of scope and the object in the heap is then available for garbage collection
Case 2 : Objects instantiated in a method are stored in the stack then are available for garbage collection when function finishes
I strongly suspect its case 1, it wouldn't make sense to store an object in a stack, the only reason I have doubts is because ive come across some literature saying on the stack and others on the heap
Thanks for your feedback ahead of time
The local reference variable is on the stack, and the object is in the heap.
Note that your question title,
Instance declared inside of a Method
is misleading since objects/instances are declared nowhere -- only variables are, and the object created in a method can be placed on fields into a collection, or anywhere it's needed. And so there is no guarantee that the object should be GC'd when the method exits.
All the objects are stored in the heap ... the garbage collector runs whenever there's a lack of memory so it get rid of the objects that are not used anymore and there's no reference to them too.
Your assumption specified in Case 1 is correct. Here is a good source on memory allocation in java.
Java Heap Space vs Stack – Memory Allocation in Java
If they are not immediate "values" (not like an int property in a class object), only their reference values are stored in the stack. their actual values and structures are stored in the heap.
these are stored in the stack as they are;
int i=10;
float f=10.00;
bool b=true;
these will have only references on the stack, they will reside in the heap (any kind of class variable is part of the structure and be created on the heap altogether);
int[] ii={1,2,3};
double[] dd = new double[10];
String s="String!!";
Object o=new Object();
when passed to a method, Values are copied to a new stack variable (unless converted to a reference object). References are also passed to a copycat stack variable, but since they are references, both will redirect to the same object (unless copied to a whole new object manually).
this part might not be of interest in the topic, you decide
In the following code, number is created on the stack and copied to a new stack value for the method, hello created on the heap, passed by reference to s then two strings concatenated on another heap address and it now holds this new address (strings are immutable). The Point object is not immutable as strings, so it can be changed anywhere you referenced it as they are created on the heap to access freely.
class Point{ int x;int y; Point(int x,int y){this.x=x;this.y=y;} }
public class TestClass{
public static void main(String []args){
int number=5;
String hello="Hello";
Point point = new Point(2,4);
Print(number,hello,point);
System.out.println(hello+" "+number+" "+point.x+" "+point.y);
}
public static void Print(int i,String s,Point p){
i+=5;
s+="World!";
p.x+=2; p.y+=2;
System.out.println(s+" "+i+" "+p.x+" "+p.y);
}
}
I do know that in Java, (perhaps in .net too) , primitives are stored on stacks , where as reference types are stored on heaps.
My question was that I do not understand the proc/cons for this behavior. Why can't we reference a memory location inside our stacks instead? . I couldn't find a proper explanation as I googled ( maybe I suck at it) , but if you people can provide some insights I would be grateful
Thanks.
I do know that in Java, (perhaps in .net too) , primitives are stored on stacks , where as reference types are stored on heaps.
No. It does not depend on whether its a primitive or a reference. It depends on the scope whether the stack or the heap is used. Local variables are allocated on the stack, member variables are allocated on the heap when the object is instantiated.
See also Do Java primitives go on the Stack or the Heap?
My question was that I do not understand the proc/cons for this behavior.
Data stored on the stack only lives as long as your method is executing. Once the method is done, all data allocated on the stack is removed.
Data stored on the heap lives as long as it is not discarded (which, in case of Java, is done in the background by the garbage collector). In other languages as C/C++, you explicitly need to delete/free data which was allocated on the heap.
Consider the following code snippet:
String someMethod() {
int i = 0;
String result = "Hello";
i = i + 5;
return result;
}
Here, a primitive (int i) is created on the stack and some calculation is done on it. Once the method finishes, i cannot be accessed anymore, and its value is lost. The same is basically true for the result reference: the reference is allocated on the stack, but the Object (a String object in this case) is allocated on the Heap. By returning the reference as return value, the object it references can still be used outside the method.
You can't generally store reference types on stack because the stack frame is destroyed upon method return. If you saved a reference to an object so it can be dereferenced after the method completes, you'd be dereferencing a non-existent stack location.
The HotSpot JVM can perform escape analysis and, if it determines that an object cannot possibly escape the method scope, it will in fact allocate it on the stack.
where as reference types are stored on heaps.
I don't know what exactly you mean by that part, but remember that, only objects are stored on heap, whereas, references pointing to those objects are still on the stack. Probably this was the doubt you had.
Now, you should also note that, only local variables are stored on stack, whereas instance / member variables are stored on Heap.
For e.g.: -
String str = new String("Rohit"); // Local variable
In above case, str reference will be allocated memory on stack, if of course it is defined in some local scope. And it will point to a new string object created on Heap.
Why can't we reference a memory location inside our stacks instead?
You can but think of this decision as Memory Architecture decision.
By concept, ideally, any data can't be retrieved from stack if it is not on top of it. But in real world you require some location to be accessed from anywhere in the program. So, it can't be stack. and they named it heap.
This link may throw more light on it.
I understand that variables of a method are stored in stack and class variables are stored in heap. Then where does the classes and objects we create get stored in Java?
Runtime data area in JVM can be divided as below,
Method Area : Storage area for compiled class files. (One per JVM instance)
Heap : Storage area for Objects. (One per JVM instance)
Java stack: Storage area for local variables, results of intermediate operations. (One per thread)
PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread)
Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread)
Following are points you need to consider about memory allocation in Java.
Note:
Object and Object references are different things.
There is new keyword in Java used very often to create a new object. But what new does is allocate memory for the object of class you are making and returns a reference. That means, whenever you create an object as static or local, it gets stored in heap.
All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap.
Classes loaded by ClassLoader and static variables and static object references are stored in a special location in heap which permanent generation.
Local primitive variables, local object references and method parameters are stored in stack.
Local Functions (methods) are stored in stack but static functions (methods) goes in permanent storage.
All the information related to a class like name of the class, object arrays associated with the class, internal objects used by JVM (like Java/Lang/Object) and optimization information goes into the Permanent Generation area.
To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems.
All objects in Java are stored on the heap. The "variables" that hold references to them can be on the stack or they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.
The Class objects that define Classes are also heap objects. They contain the bytecode that makes up the class (loaded from the class files), and metadata calculated from that.
The Stack section of memory contains methods, local variables and reference variables.
The Heap section contains Objects (may also contain reference variables).
after short google, I found a link to describe it, yes a youtube video link. ^_^
http://www.youtube.com/watch?v=VQ4eZw6eVtQ
The concept is quite simple :
Instance variables (primitive, Wrapper classes, references, objects (non-static)) - Heap
Local Variables , references - stack
Other data objects like : Class metadata, JVM code, static variables, static object references, static functions etc which earlier used to be in Permgen Space (till Java 7) are now being moved to Metaspace in JAVA 8.
PS : Metaspace is part of native memory, so no need to worry about OOM:Pergem Exeption now.
For more details : https://siddharthnawani.blogspot.com/
Local variables(method variables) + methods live on the stack. While Objects and their instance variable live on the heap.
Now, Reference variable can be local variable(if created inside method) or instance variable(if created inside class, but outside method). So reference variable can be anywhere, either stack or heap.
According to JVM Specification,
The classes and it's own constant pool, i.e static variables are stored in Method Area.
Here class means nothing but bunch of fields, methods and constants, these methods are in the form of instructions are stored in Method Area and can be identified by an address.
Objects are nothing but a filled class template that will be created in Heap Area, but the object reference is created in Stack.
public class Sample{
int field;
static int constant;
public void test(){
int localVariable=10;
Sample samp=new Sample();
}
}
In the example,
sample.class will go to Method Area, that means 'field', 'constant' and method 'test' are allocated in Method Area.
When the execution is started,
The object created by new Sample() will go to Heap but 'samp' is just a object reference which goes to stack and holds the address of object which is present in the Heap
For more information please check this link,
JVM Specification
In Java, a variable can either hold an object reference (s in String s="OOO" holds the reference to the object "OOO") or a primitive value (i in int i=10 holds 10). These variables can either be on the heap or the stack, depending on whether they are local or not and which flavor of the JVM you are using.
In the Java Virtual Machine 8 specification document (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html), the memory organization pertaining to this is as follows.
Every Java thread has its own JVM stack.
It holds local variables and partial results, and plays a part in
method invocation and return.
There may be object references as well in the stack. The
specification does not differentiate between a primitive variable
and a reference variable as long as it is local. This stack is used using
units of data called frames. However,
Because the Java Virtual Machine stack is never manipulated directly
except to push and pop frames, frames may be heap allocated.
Therefore, it is upto the implementation of the JVM specification (like OpenJDK or Oracle), where the frames are located.
Every JVM instance has a heap. The heap is
... the run-time data area from which memory for all class instances and
arrays is allocated.
The actual memory holding the objects' data resides on the heap. The
heap is shared among all the JVM's threads. This also includes object
references which are part of objects ie instance variables.
For example, take the following classes.
class Moo{
private String string= "hello";
}
class Spoo{
private Moo instanceReferenceVariable = new Moo();
public void poo(){
int localPrimitiveVariable=12;
Set<String> localReferenceVariable = new HashSet<String>();
}
}
Here the object being referred to by the variable instanceReferenceVariable
would be on the heap, and hence all the instance variables of this object, like
string, will also be on the heap. Variables localPrimitiveVariable and
localReferenceVariable will be on the stack.
Method Area: The method area is a restricted part of the heap which
... stores per-class structures such as the run-time constant pool,
field and method data, and the code for methods and constructors,
including the special methods used in class and instance
initialization and interface initialization.
Run-time constant pool: This is a part of the method area.
Hope this was able to clarify things.
I am thinking about memory allocation in Java i.e in which
memory location methods, fields and objects are stored.
Suppose I have 2 classes
import java.util.*;
class ABC
{
int field;
List<Integer>l;
}
class XYZ
{
int x,y,z;
static int p;
void fun(ABC a){
a.field = 10;
a.l = new ArrayList<Integer>(10);
a.l.add(10);
}
}
public class Simulator{
public static void main(String[] arg){
XYZ tmp_1 = new XYZ();
ABC tmp_2 = new ABC();
tmp_1.fun(tmp_2);
System.out.println(tmp_2.l);
}
}
Now where will the memory be allocated for each of the data members,functions and objects be allocated ?
My thoughts are objects, data-members will be stored in Heap but I am not sure about functions and their data members ?
Yes, all objects are allocated on the heap. I.e.: everything created with new will be placed on the heap. All fields of such objects are thus also on the heap.
I suppose you are referring to local variables and parameters in functions. These are placed on the stack (for each call of the function). Note, however, that when function variables/parameters are of reference types then the actual object they point to is on the heap but the variable/parameter itself will be on the stack (similar to a pointer in C/C++). On the other hand, function variables/parameters of primitive types (like int, double, etc.) will be entirely on the stack. A slightly related but relevant to the topic is the concept of boxing.
Functions themselves are static code and are stored in a special part of the memory where all executable code resides. Note that all instances of a class share the same functions (i.e. "new functions" are not created with newly created objects, even if these functions are instance functions). Thus, when you call an instance function on an object, a special this reference is passed to that function (it's an implicit argument to the function). This is how the function knows on which objects it should act.
Here's a breakdown of how the different things that you refer or allude to are stored:
Local variables and method / constructor parameters can contain either primitive values or references to objects or arrays. (They cannot contain the objects or arrays themselves.) Locals and parameters are stored in activation frames (to use the JLS terminology), and these frames are stored on a thread's stack. Thread stacks are non-heap memory in typical JVMs.
Objects and arrays are represented in heap memory.
Instance fields (containing primitive or reference values) are stored in objects, and hence in the heap.
Array elements (either primitive or reference values) and the length of an array are stored in the array and hence in the heap.
Static fields are stored in special frames called static frames. These frames are stored in the heap.
The code of Java methods (in byte-code and native code form) is typically represented by code blocks that are stored in the heap.
Note that the above is based on what happens in a typical JVM. In fact, the Java Language Specification does not mandate that things are stored in a stack or a heap. The terms stack memory and heap memory hardly appear in the JLS at all, and it is conceivable that other memory organization schemes could be used.
Also, "the heap" is an over-simplification, because a HotSpot JVM / GC typically divides the heap into areas with different characteristics. For instance the "permgen" area of the heap (where static frames and code blocks are allocated) is only garbage collected rarely.
To complement previous answer:
The functions are stored in special area, but a reference to them is stored in the object (for non static functions).
Reference to static functions is stored in another area (you can think they are stored just next to static fields) (static memory area).
All objects are stored in heap (Object Pool), but the place of reference to them vary, local variables are in the stack, non static fields are stored in the object itself, so they are stored in the heap too.
Static references are placed in another special part of the memory, (although if they are references to Objects, they point to heap).
I am currently learning the memory concepts of java, the stack and the heap, I know that local variables and method calls lived in a place called stack. and objects lived inside a heap. but what if that local variable holds an object? or has an object reference?
public void Something(){
Duck d = new Duck(24);
}
Does it still live inside a stack? and where do instance variables live? please keep it simple as possible. thank you.
Local variable d (allocated on stack) contains a reference to an object of class Duck. In general objects are allocated on the heap.
Java 6e14 added support for something called 'escape analysis'. When you enable it with -XX:+DoEscapeAnalysis switch, then if JVM determines that an object is created in a method, used only in that method and there is no way for reference to the object to 'escape' that method - that is, we can be sure that the object is not referenced after method completes - JVM can allocate it on stack (treating all its fields as if they were local variables). This would probably happen in your example.
Fields are allocated with the rest of the object, so on the heap or on the stack, depending of escape analysis results.
Object reference variables work. just like primitive variables-if the reference is declared as a local variable, it goes on the stack.else if refrence is instance variable it will go into the heap within an object.