Java Heap and Stack

Source: Internet
Author: User

   The Java heap is a run-time data area in which objects allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data.    However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time. The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variables (, int, short, long, byte, float, double, Boolean, char) and object handle. Stack has a very important particularity, is that there is data in the stack can be shared. Suppose we define both: int a = 3; int b = 3; the compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds the value of 3 in the stack, and if not found, stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3. At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B. It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving. An object reference variable modifies the internal state of the object, affecting another object reference variable. String is a special wrapper class data. Can be used: string str = new String ("abc"); String str = "ABC"; Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made. The second is to create an object reference to the string class in the stack str, and then find whether there is no "ABC" in the stack, if not, put "ABC" into the stack, and make str point to "ABC", if there is already "ABC" directly to the "ABC" Str. When comparing values within a class, use Equals () method, when testing the reference of two wrapper classes to point to the same object, use = =, the following example illustrates the above theory. String str1 = "abc"; String str2 = "abc"; System.out.println (STR1==STR2); True to see that str1 and str2 are pointing to the same object. String str1 =new string ("abc"); String str2 =new string ("abc"); System.out.println (STR1==STR2); False the new method is to generate different objects. Each time one is generated. Therefore, the first way to create multiple "abc" strings, in memory there is only one object. This writing is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual data in the stack. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program. On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time.  Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when a string variable needs to change its value frequently.

Other answers:

A

First, from the point of view of software design, the stack represents the processing logic, and the heap represents the data. This separation makes the processing logic clearer. The idea of divide and conquer. This idea of isolation and modularity is reflected in every aspect of software design. Second, the separation of the heap from the stack allows the contents of the heap to be shared by multiple stacks (and can also be understood as multiple threads accessing the same object). The benefits of this sharing are many. On the one hand, this kind of sharing provides an effective way of data interaction (for example: Shared memory), on the other hand, the shared constants and caches in the heap can be accessed by all stacks, saving space. Third, the stack because of the needs of the runtime, such as saving the context of the operation of the system, the address segment needs to be divided. Because the stack can only grow upward, it restricts the ability to store content on the stack. While the heap is different, the objects in the heap can grow dynamically as needed, so the stack and heap splits make the dynamic growth possible, and only one address in the heap is required to be recorded in the corresponding stack. The object-oriented is the perfect combination of heap and stack. In fact, the object-oriented approach to the implementation of the previous structured program is not any different. However, the introduction of object-oriented, so that the way to think about the problem has changed, and closer to the natural way of thinking. When we take the object apart, you will find that the object's properties are actually data, stored in the heap, and the object's behavior (method) is running logic, placed in the stack. When we write the object, we write the data structure, and also write the logic of the processing. I have to admit, object-oriented design is really beautiful.

Two

The heap is FIFO first, while the stack is advanced after 1. Stacks and heaps (heap) are places that Java uses to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps. 2. The advantage of the stack is that the access speed is faster than the heap, second only to the registers directly in the CPU. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. In addition, the stack data can be shared, see 3rd. The advantage of the heap is that the memory size can be allocated dynamically, and the lifetime does not have to tell the compiler beforehand that the Java garbage collector automatically collects the data that is no longer in use. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time

(iii)

Java divides memory into two types: one is stack memory, and the other is heap memory. Some of the basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function. When a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable, which can be used immediately by another. Heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine. After generating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program.

Four

Heap: Used to store new things stack stack: local variables. Data segment: Static variable, string constant. Code segment: Storing Codes

(v)

for example, string str = new string ("Test"), which is the execution of a string object with a value of "test" on the heap, and a new str on the stack to point to the new "test" object above, that is, STR is " Test "reference. So the new objects in Java are all built on the heap, and the object references are generally on the stack. In general, each method's call will have a separate stack to hold the reference variable of an object such as STR, after the method returns, the stack will be emptied, so the reference variable will be emptied, this is the object on the heap, if there is no other reference variable reference it, it will be GC at some appropriate time GC off. It says that the stack and the heap are in the process of executing the program.  

Six

The heap is allocated on the variable size of the object, the size of the base data type (Int,short) is on the stack, the size of the object on the stack is fixed on the heap on the object's reference is also on the stack, if the heap of objects on the stack without references, he was collected by GC

Seven

(eight)

>>> Stacks. resides in the general RAM (random access memory) area, but can be directly supported by its "stack pointer" for processing. If the stack pointer moves down, the new memory is created, and if you move up, the memory is freed. This is a particularly fast, particularly effective way to save data, second only to registers. When you create a program, the Java compiler must know exactly the "length" and "time of existence" of all data saved in the stack. This is because it must generate the appropriate code to move the pointer up and down. This restriction undoubtedly affects the flexibility of the program, so although some Java data is stored in the stack-especially the object handle-the Java object is not placed in it. >>> Heap. A general-purpose memory pool (also in the RAM area) in which Java objects are saved. Unlike stacks, the most appealing aspect of the heap is that the compiler does not have to know how much storage to allocate from the heap, or how long the stored data will stay in the heap. As a result, there is greater flexibility in storing data with heaps. When you require an object to be created, you only need to compile the relevant code with the new command. When the code is executed, the data is saved automatically in the heap. Of course, there is a certain price to be paid to achieve this flexibility: it takes longer to allocate storage space in the heap!

(ix)

I. Preliminary knowledge-memory allocation of the program
The memory used by a program compiled by C + + is divided into the following sections
1. Stack (stack)-Automatically allocated by the compiler to release, store the function parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the end of the program may be recycled by the OS. Note that it is not the same as the heap in the data structure, the distribution is similar to the list, hehe.
3, Global Zone (Static)-, the storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another area adjacent. -System release after the program is finished
4, literal constant area-the constant string is put here. Released by the system after the program is finished
5. Program code area-binary code that holds the function body.

Ii. Examples of procedures
It was written by a predecessor, very detailed
Main.cpp
int a = 0; Global initialization Zone
Char *p1; Global uninitialized Zone
Main ()
{
int b; Stack
Char s[] = "ABC"; Stack
Char *p2; Stack
Char *p3 = "123456"; 123456 in the constant area, p3 on the stack.
static int c = 0; global (static) initialization zone
P1 = (char *) malloc (10);
P2 = (char *) malloc (20);
Areas that are allocated 10 and 20 bytes are in the heap area.
strcpy (P1, "123456"); 123456 in the constant area, the compiler might optimize it to a place with the "123456" that P3 points to.
}


Ii. theoretical knowledge of heaps and stacks
2.1 How to apply
Stack
Automatically assigned by the system. For example, declare a local variable int b in the function; The system automatically opens up space for B in the stack
Heap
Requires the programmer to apply himself and indicate the size of the malloc function in C
such as P1 = (char *) malloc (10);
Using the new operator in C + +
such as P2 = (char *) malloc (10);
But note that P1, p2 itself is in the stack.
2.2
Response of the system after application
Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
Heap: First you should know that the operating system has a list of idle memory addresses, when the system receives the application of the program,
The list is traversed to find the first heap node that is larger than the requested space, and then the node is removed from the list of idle nodes, and the space of that node is allocated to the program, and for most systems the size of this allocation is recorded at the first address in the memory space, so that The DELETE statement in the code can properly free up this memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.
2.3 Application Size Limits
Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.
Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.
2.4 Comparison of application efficiency:
The stack is automatically assigned by the system and is faster. But programmers can't control it.
Heap is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use.
In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor in the stack is directly in the process's address space to keep a fast memory, although the most inconvenient to use. But it's fast and flexible.
2.5 Storage contents in stacks and stacks
Stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack.
When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.
Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.
2.6 Comparison of access efficiency

Char s1[] = "AAAAAAAAAAAAAAA";
Char *s2 = "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA is assigned at run time;
And BBBBBBBBBBB is determined at compile time;
However, in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).
Like what:
#include <stdio.h>
void Main ()
{
char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
Return
}
The corresponding assembly code
10:a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]
0040106A 4D FC mov byte ptr [ebp-4],cl
11:a = p[1];
0040106D 8B-EC mov edx,dword ptr [ebp-14h]
00401070 8A mov al,byte ptr [edx+1]
00401073 FC mov byte ptr [ebp-4],al
The first reads the elements in the string directly into the register CL, while the second one reads the pointer values into EDX, which is obviously slow to read the characters according to EdX.
?

2.7 Summary:
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

The difference between heap and stack is mainly divided into:
The operating system stack and stack, as said above, not much to say.
There are heaps and stacks of data structures that are different concepts. The heap here actually refers to a data structure of the priority queue (which satisfies the heap nature), the 1th element has the highest priority, and the stack is actually a mathematical or data structure that satisfies the advanced nature of the post.
Although stacks, stacks are said to be linked together, but they are still very different, connected to call only because of historical reasons.

Java Heap and Stack

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.