Difference between Java stack and java stack

Source: Internet
Author: User

Difference between Java stack and java stack

Variables of some basic types defined in the function and referenced variables of the object are allocated in the function stack memory.

 

When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.

 

Heap memory is used to store objects and arrays created by new.

 

The memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector.

 

After an array or object is generated in the heap, you can define a special variable in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, the variable in the stack becomes the referenced variable of the array or object.

 

The referenced variable is equivalent to an array or an object name. Later, you can use the referenced variable in the stack in the program to access the array or object in the heap.

 

Variable Allocation in memory in java

 

1. class variables (static modified variables): when a program is loaded, the system opens up memory for it in the heap. The memory address in the heap is stored in the stack for high-speed access. The lifecycle of static variables-until the entire "system" is disabled

 

2. instance variables: when you use the java keyword new, the system opens up in the heap and does not necessarily allocate continuous space to variables (such as class instances ), then, based on the scattered heap memory address, the hash algorithm is used to convert a long string of numbers to represent the "physical location" of the variable in the heap ". Instance variable lifecycle-When instance variable reference is lost, the GC (Garbage Collector) will be included in the recyclable "list", but the heap memory will not be released immediately

 

3. Local variables: local variables are defined by opening up the memory in the stack when they are declared in a method or in a code segment (such as a for loop, when local variable 1 is out of scope, the memory is released immediately

 

Appendix: java memory mechanism

 

Java divides memory into two types: stack memory and heap memory.

Some of the basic types of variables defined in the function and the referenced variables of the object are allocated in the function stack memory. When a variable is defined in a block of code, java allocates memory space for this variable in the stack. When the scope of the variable is exceeded, Java Automatically releases the memory space allocated for this variable, the memory space can be used as another memory immediately.

Heap memory is used to store the objects and arrays created by new, and the memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector. After an array or object is generated in the heap, you can define a special variable in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, this variable in the stack becomes an array or object reference variable. Later, you can use the reference variable in the stack in the program to access the array or object in the stack, the referenced variable is equivalent to an array or object name. The referenced variable is a common variable. It is assigned to the stack during definition. The referenced variable is released after the program runs out of its scope. Arrays and objects are allocated in the heap. Even if the program runs beyond the code block where new statements are used to generate arrays or objects, the memory occupied by arrays and objects is not released, arrays and objects become junk only when no referenced variable points to it. They cannot be used, but still occupy the memory space, the garbage collector collects (releases) the garbage collector at an uncertain time ).

This is also the reason why Java accounts for memory. In fact, the variables in the stack point to the variables in the heap memory, which is the pointer in Java!

 

 

Both stacks and stacks are places where Java is used to store data in RAM. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks.

The Java heap is a runtime data zone, from which the class objects allocate space. These objects are created using commands such as new, newarray, anewarray, and multianewarray. They do not need program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told in advance because the heap dynamically allocates memory at runtime, the Java Garbage Collector automatically collects the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.

The advantage of stack is that the access speed is faster than that of stack, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. The stack mainly stores some basic types of variables (, int, short, long, byte, float, double, boolean, char) and object handles.

A very important feature of stacks is that data in stacks can be shared. Suppose we define both:

Int a = 3;

Int B = 3;

The compiler first processes int a = 3. First, it creates a reference with the variable a in the stack, and then finds whether the value 3 in the stack exists. If no value is found, store 3 and point a to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time.

At this time, if a is set to 4 again, the compiler will re-search whether there are 4 values in the stack. If not, it will store 4 and make a point to 4; if yes, direct a to this address. Therefore, changing the value of a does not affect the value of B.

Note that the sharing of data is different from the sharing of two objects pointing to one object at the same time, because the modification of a does not affect B, which is completed by the compiler, it facilitates space saving. A variable referenced by an object modifies the internal state of the object, which affects the variable referenced by another object.

String is a special packaging data. Available:

String str = new String ("abc ");

String str = "abc ";

The first method is to use new () to create an object, which is stored in the heap. Each call creates a new object.

The second is to first create a String class object in the stack to reference the variable str, and then find whether the stack contains "abc". If not, store "abc" into the stack and point str to "abc". If "abc" already exists, direct str to "abc ".

Use the equals () method to compare the values in a class. Use the = method to test whether the references of the two classes point to the same object. The example below illustrates the above theory.

String str1 = "abc ";

String str2 = "abc ";

System. out. println (str1 = str2); // true

It can be seen that str1 and str2 point to the same object.

String str1 = new String ("abc ");

String str2 = new String ("abc ");

System. out. println (str1 = str2); // false

The new method is used to generate different objects. Each time one is generated.

Therefore, the first method is used to create multiple "abc" strings. Only one object exists in the memory. this method is advantageous and saves memory space. at the same time, it can improve the program running speed to a certain extent, because the JVM will automatically decide whether to create a new object based on the actual situation of the data in the stack. For the code of String str = new String ("abc");, a new object is created in the heap, regardless of whether the String value is equal, whether it is necessary to create a new object, this increases the burden on the program.

On the other hand, NOTE: When we define classes using formats such as String str = "abc";, we always take it for granted that the str object of the String class is created. Worry trap! The object may not be created! Instead, it may only point to a previously created object. Only by using the new () method can a new object be created every time.

Because of the immutable property of the String class, when the String variable needs to change its value frequently, you should consider using the StringBuffer class to improve program efficiency.


System Response after application
STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

Application size limit
STACK: in Windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is 2 MB (OR 1 MB, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow is displayed. Therefore, the space available from the stack is small.
.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.


Comparison of application efficiency:
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.
In addition, in WINDOWS, the best way is to use VirtualAlloc to allocate memory. Instead of heap or stack, it is to reserve a fast memory in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.

Storage content in heap and stack
STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack.
When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.
Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

Comparison of access efficiency

Char s1 [] = "aaaaaaaaaaaaa ";
Char * s2 = "bbbbbbbbbbbbbbbbb ";
Aaaaaaaaaaa is assigned a value at the runtime;
Bbbbbbbbbbbbb is determined during compilation;
However, in future access, the array on the stack is faster than the string pointed to by the pointer (such as the heap.
For example:
 

Void main ()
{
Char a = 1;
Char c [] = "1234567890 ";
Char * p = "1234567890 ";
A = c [1];
A = p [1];
Return;
}
Corresponding assembly code
 

10: a = c [1];
00401067 8A 4D F1 mov cl, byte ptr [ebp-0Fh]
0040106A 88 4D FC mov byte ptr [ebp-4], cl
11: a = p [1];
0040106D 8B 55 EC mov edx, dword ptr [ebp-14h]
00401070 8A 42 01 mov al, byte ptr [edx + 1]
00401073 88 45 FC mov byte ptr [ebp-4], al
The first method reads the elements in the string directly to the cl register, while the second method reads the pointer value to the edx.
Reading characters by edx is obviously slow.


Summary:
The difference between stack and stack can be seen in the following metaphor:
Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it). If you are full, you can leave, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small.
Using heap is like making your favorite dishes. It is troublesome, but it suits your taste and has a high degree of freedom.

 

References:

Http://blog.163.com/xyw198610@126/blog/static/362212432008101733733554/

Http://www.cnblogs.com/perfy/p/3820594.html

Copyright statement: I feel very grateful if I still write well, I hope you can use your mouse and keyboard to give me a thumbs up or give me a comment! _______________________________________________________________ You are welcome to reprint. I hope to add the original address while you reprint it. Thank you for your cooperation.

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.