This might seem a lot of questions but they are all interrelated.I'm little confused as in where is the heap space allocated and where is the stack memory located ? If both are present in main memory then why it is said that stack memory is easier to access and why can't we allocate objects in stack memory ? Since classes are stored in PermGen where is this space allocated and how does it differ from heap space and where are constant strings stored ?
"Where are the heap and stack allocated?" The accepted answer to this question covers this. Each thread gets its own stack and they all share one heap. The operating system controls the exact memory locations of the stacks and heap items and it varies.
"Why is stack memory easier to access" Each thread has its own stack, so there are fewer concurrency issues. The stack and heap are both eligible for caching in the L1, L2, and L3 portions of the memory hierarchy, so I disagree with Daniel's answer here. Really I would not say that one kind of memory is particularly easier to access than the other.
"Why can't we allocated objects in stack memory?" This is a design decision taken by the JVM. In other languages like C/C++ you can allocate objects on the stack. Once you return from the function that allocated that stack frame such objects are lost. A common source of errors in C/C++ programs is sharing a pointer to such a stack allocated object. I bet that's why the JVM designers made this choice, though I am not sure.
The PermGen is another piece of the heap. Constant strings are stored here for the lifetime of the JVM. It is garbage collected just like the rest of the heap.
If both are present in main memory then why it is said that stack memory is easier to access
There's speed of access and speed of allocation. Stack allocation (as in alloca) is fast because there's no need to search for an unused block of memory. But Java doesn't allow stack allocation, unless you count the allocation of new stack frames.
Accessing stack memory is fast because it tends to be cached. Not only are locals near one another, they are also stored very compactly.
and why can't we allocate objects in stack memory ?
This would be useful, but dangerous. A user could allocate an object on the stack, create references to it from permanent objects, and then try to access the object after the associated stack frame is gone.
It's safe to store primitives on the stack because we can't create references to them from elsewhere.
Since classes are stored in PermGen where is this space allocated and how does it differ from heap space and where are constant strings stored ?
PermGen is just another heap space. String literals are stored in the literal pool, which is just a table in memory which is allocated when a class is loaded.
Related
I am investigating JVM architecture and its working behind the scenes.
I have heard a lot of times that stack stores method return types, operands, local variables and references to objects.
But while reading the Oracle specification I have found the picture where drawn that stack frame has no references to objects directly but the reference to the constant pool.
Am I understanding correctly that stack has the reference to the reference to the objects in heap or not?
Frame - is a part of stack.
Each frame has its own array of local variables (§2.6.1), its own
operand stack (§2.6.2), and a reference to the run-time constant pool
(§2.5.5) of the class of the current method.
From this explanation I can understand that in order to get an adress of object in the heap we need to find it in the run-time constant pool.
Link to the Oracle specification - https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html
Stack can contain pointers to heap and constant pool(by the way this is also logically in the heap accoring to JVM spec). Implementation specific these pointers can point to objects or to pointers that points to the objects.
Implementation of the garbage collector can effect this behaviour. For example Shenandoah Gc uses additional pointers for accesing objects(*) . With this implementation a pointer (gc root) in the stack points to another pointer that points to actual object. Oracle Jvm is not implemented like this.
(*) Details of the implementation;
Objects in the heap can be moved to different memory locations during garbage collection. For example objects in the eden space can be moved to survivor space and then to old generation.
With this information, lets say an object is pointed by 10 pointers, if this object's memory address is changed, 10 pointers should be updated to point to correct address. If the pointers, points to a forwarding pointer, and that forwarding pointer points to object; only updating the forwarding pointer is required this time. Aim of the forwarding pointer approach is reducing the garbage collection pause times.(at the cost of lower throughput)
There is an explaination of this process in the following video.
https://youtu.be/AAiB3fDwyRM?t=424
https://wiki.openjdk.java.net/display/shenandoah/Main
https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5.4
This question already has answers here:
What does the `new` keyword do
(9 answers)
Closed 6 years ago.
How new operator allocates memory for the object in Java? it was asked what happen if we write
Test t= new Test().
How the new operator will work to allocate memory internally in heap memory? Might be some steps.
The implementation is JVM dependant. There is a number of possible outcomes.
if the object isn't needed, it might be eliminated i.e. nothing happens.
if Escape Analysis detects the object doesn't escape a method, it can place it on the stack. This allocation happens when the frame is started and all the memory needed is reserved at once (not per object)
if you have TLAB (Thread Local Allocation Buffers) enabled (which is by default), each thread has a local buffer from which to allocate objects. This allows concurrent memory allocation. It has a pointer the next free space in the buffer and when a new object is added it takes the pointer and adds the size of the object. It zeros out the object as well (and sets up the object header). New buffers are allocated from the Eden space (except in G1 where it gets an empty chunk of memory)
if you don't have TLABs, allocation is taken directly from the eden space.
I was wondering- when defining a new stack through the stack class
Stack stack=new Stack();
How much memory is allocated to it? It cannot depend on the amount of N objects (like arrays and lists, for example) because it is initialized without any data regarding the amount of objects that would be placed in.
However, it also doesn't make a lot of sense that it'd have a fixed amount of memory like an intor double for example, because you constantly place objects in it.
Does push command increases the memory allocation of the stack?
I assume it is placed in the 'heap' memory?
Thanks!
I'm speaking from C#, so bear with me; Whenever you allocate memory for a local variable, it gets allocated on the stack, heap is for things like objects, which allocates a reference to the object and then the actual object, then the object reference gets used by the garbage collector to go through and figure out what objects need to be cleaned up and which ones don't.
In this case, I believe you are allocating the object on the heap, because all a "stack" object is, is a filo data structure.
Stacks in Java only store primitives that exist within a local scope, ergo the stack size in Java is usually pretty small, the size however depends on several factors and is variable at runtime, the initial size for example is typically calculated based on how much memory the compiler thinks it will need to run, then as it grows it will increase in size (I think Windows for example increases the stack by pages, which is 256 bytes of memory, but don't hold me to that.)
In your case, since you are asking about the initial size of an uninitialized stack object, the size is the size of the stack object, and it changes as you add elements to it.
Hope that helps.
Stack extends Vector, and Stack() calls Vector() implicitly, which uses a default initial capacity of 10.
Stack inherits from Vector. The default constructor of Vector initializes an array with size 10.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Explain the difference between contiguous allocation (memory held in a heap in the stack) vs. memory in a heap.
I'm new at this and not entirely sure.
The question isn't contiguous versus heap, but automatic versus heap.
Automatic storage is set up on entry to a block of code -- traditionally on entry to a function or method -- and discarded when that function returns, so its memory space on the stack can be reused by the next function call. That's how most local variables are handled. Obviously this isn't useful for anything which is intended to persist past the end of that function call.
In Java, objects are never allocated from automatic storage. Instead, they are allocated from the heap, on demands, when the new operation is performed. There are several reasons for this which, frankly, unless you're designing a programming language you don't really need to know about and it's too large a topic to cover here. The important thing is that since they were obtained from the heap, their lifetime is independent of the stack frame. Since Java is a garbage-collected language, their memory will be automatically recovered for reuse sometime after that last reference to them goes away -- again, the details are too large a topic to cover here, but basically you can trust that the GC comes through periodically to pick up the clothes we dropped on the floor and toss them into the laundry.
A stack frame only exists for the life of a method call, which means that memory is allocated to provide storage for all your local variables and method parameters that are used in some way that assist helping the method achieve its goals of whatever task it set out to achieve.
Examples of memory storage in a stack frame are temporary pointers that are used to keep track of an index position in an array which you are iterating through. Once the loop is finished, the stack frame would be popped off the stack, which means all the temporary memory allocated for the local variables and method parameters that existed are released back into the system.
The heap is different because it is where objects live, not "pointers" to objects.
When I was learning I found it hard to work out the difference between the two.
The key point that helped me was that, a pointer to an object is kept in a stack frame, it has a little bit of temporary memory allocated that exists for the life time of the method call. Thus, you can only access an object when the method is in "scope".
The pointer contains a memory address that leads to the location of the object stored on the heap. This allows you to reference the object to change the objects state at a later time.
public static void main(String[] args)
{
Person person = new Person("Steven", 30);
}
When you run this program:
new keyword means java will allocate memory on the heap for the space required to store the Person objects instance variables.
The important part to understand is, no memory is required to store an objects methods. When a method is called, a new stack frame is created which allocates temporary memory for the duration of the method call. Using the example above, a Person has 2 instance variables, a String name and int age. This means that the memory required for this Person object is the required memory to store a reference variable of type String (bit pattern of the memory address of a String object on the heap) and memory to hold the bit pattern of an int.
Lastly, the main method is a stack frame too, so when main finishes, you no longer have a reference to a Person object or access to any temporary variables that may have existed in main.
This is true for any method, if you have a method that creates an object but doesn't return the reference to that object, then you can never access the object and the java garbage collector comes along at a later time and cleans up all the objects on the heap that don't have references pointing to them.
If you are starting out, I highly recommend head first java. It is a great book IMO and covers these topics in easy to understand ways.
When we talk about memory or disc allocation, the word "contiguous" simply means "without any gaps".
A single stack or heap memory allocation is always contiguous ... in every programming language runtime I've ever encountered where it makes sense to talk about allocations at all.
A sequence of allocations is contiguous if there is no gap between the individual allocations.
This is orthogonal to stack versus heap. Both stack allocations and heap allocations can be contiguous ... or non-contiguous.
Well ... not quite orthogonal.
If you are talking about strictly contiguous memory addresses (physical or virtual), a typical heap node consists of the area of memory that the application can use, plus a small node header. So, if you look at the available memory for two consecutive heap nodes, there is a gap ... comprising the node header ... that prevents the two regions being used by the application as a single contiguous region. (And you'd better not try 'cos if you overwrite the node header, bad things could happen.)
However, when we are talking about Java this is not relevant. Java does not allow an application to join objects or arrays together. (That would be a fundamental violation of runtime type safety.) So the notional gap in the address ranges doesn't matter. In the Java context, we would say that two objects are contiguous, ignoring the heap node / object header.
Besides, in Java you can't explicitly allocate things on the heap either. In a classical JVM, only local variables comprising primitive types and references go on the stack. There is no way to say "allocate this array on the stack". (The JVM might do the latter under certain circumstances, but it is entirely transparent to the application, and certainly not something that you could make use of.)
I've recently increase my use of the Profiler in Netbeans (6.7), this is a great tool.
I have a question however. When taking a heap dump, on the summary page (expect window) it is possible to 'find the biggest objects by retained size'.
What is this value and how is it used to analyze memory usage?
The retained size for an object is the quantity of memory this objects preserves from garbage collection.
The formal definition is "the size of the object plus the size of all objects referenced only by the first object, recursively".
For more explanations about what the retained memory is, see this article.
One easy way to remember it is that the retained memory is all the memory that could be garbage collected if this object was dereferenced.