Java heap and heap memory; Java stack memory and heap memory

Source: Internet
Author: User
Tags data structures garbage collection
Heap memory is entirely allocated and released by the JVM, and if the program has no defective code that causes memory leaks, then you will not encounter java.lang.OutOfMemoryError this error. Use of the heap of memory, is to be able to directly allocate and release memory, improve efficiency. After JDK5.0, there are 2 ways in which you can directly manipulate local memory in your code: using an unsafe and bytebuffer under NIO packets. the benefits of a heap of external memory are:

1, can be extended to a larger memory space. For example, more than 1TB or even larger than main memory space.
2, theoretically can reduce the GC pause time.
3, can be shared between processes, reduce the JVM of the object replication, making the JVM split deployment easier to implement.
4, its persistent storage can support rapid restart, but also can reproduce the production data in the test environment. The advantages of the outer heap memory:

Heap memory, in fact, is memory that is not controlled by the JVM. There are several advantages compared to the memory in the heap:
1 reduces garbage collection because garbage collection suspends other work (may use multithreading or time slices, and it doesn't feel that way)
2 speeds up the replication speed. Because the heap is internally flush to the remote, it is copied to direct memory (not heap memory) and then sent, while the outer heap memory is equivalent to omitting the work. Heap External Memory disadvantage:

And the misfortune of the blessing, Nature also has a bad side:
1 Outside of the heap memory is difficult to control, if memory leaks, it is difficult to troubleshoot
2 of external memory is relatively unsuitable for storing very complex objects. Generally simple objects or flattened more suitable. Java Stack Memory

Java divides memory into two types, one is called stack memory, the other is called heap memory

Some of the basic types of variables and objects that the

defines in a function are allocated in the stack memory of the function. When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.
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 automatic garbage collector. After generating an array or object in the heap, you can also define a special variable in the stack that equals the array or the first address of the object in the heap memory, and the special variable in the stack becomes the reference variable of the array or object. You can then use a reference variable in the stack memory in your program to access an array or object in the heap, which is equivalent to an alias, or a code name, for an array or object. A
reference variable is a generic variable that allocates memory in the stack when defined, and a reference variable is released outside the program's function. and the array and the object itself are allocated in the heap, even if the program runs to a block of code that uses new to generate arrays and objects, the heap memory occupied by the array and the object itself is not freed, and the array and object are turned into garbage and can no longer be used without reference to the variable, but still occupy memory, is released by the garbage collector at a later uncertain time. This is also a Java comparison of the main reason for memory, in fact, the variables in the stack point to the variables in the heap memory, which is the pointer in Java! Comparison of memory allocation policies and heaps and stacks in Java

1 memory allocation policy
According to the principle of compiling, there are three kinds of strategies for the memory allocation in the program runtime, which are static, stack type, and heap type.
Static storage allocation is the ability to determine the storage space requirements for each data target at run time at compile time, so that they can be allocated a fixed memory space at compile time. This allocation policy requires that the existence of variable data structures (such as variable groups) is not allowed in program code. Nested or recursive structures are not allowed to appear because they all cause the compiler to not compute the exact storage space requirements.
Stack storage allocations can also be called dynamic storage allocations, and are implemented by a stack-like run stack. In contrast to static storage allocation, in a stack storage scenario, the requirements of a program for the data area are completely unknown at compile time, only to be known at runtime, but when running into a program module, You must know the size of the data area required by the program module to allocate memory for it. Like the stacks we know about in data structures, stack storage allocations are distributed according to the advanced principle.
Static storage allocation requires the storage requirements of all variables to be known at compile time, and the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is dedicated to the inability to determine the memory allocation of the data structure of the storage requirements at compile-time or runtime module entrances. such as variable length strings and object instances. The heap is made up of large chunks of available blocks or free blocks, and the memory in the heap can be allocated and released in any order.

Comparison of 2 stacks and stacks
The above definition is summarized from the textbook of compiling principles. In addition to static storage allocation, all appear to be very stiff and difficult to understand, the following aside from static storage allocation, concentrated comparison heap and stack:
from the heap and stack functions and functions to the popular comparison, the heap is mainly used to store objects, the stack is mainly Used to execute a program. And this difference is mainly due to the characteristics of the heap and Stack decided:
in programming, such as C/s + +, all method calls are carried out through the stack, all local variables, formal parameters are allocated from the stack memory space. It's not really a distribution, it's just going up from the top of the stack, like a conveyor belt in a factory (conveyor belt), stack pointer will automatically guide you to the place where you put things, All you have to do is just put things down. When you exit the function, you can destroy the contents of the stack by modifying the stack pointer. This mode is the fastest, of course, to run the program. It is important to note that when assigning a data area for a program module that is about to be called, Should know the size of the data area in advance, it is said that although the allocation is performed while the program is running, but the size of the allocation is determined, unchanged, and this "size" is determined at compile time, not at runtime. The
Heap is an application that requests the operating system to allocate its own memory at run time. Because of the memory allocations managed from the operating system, it takes time to allocate and destroy, so the heap is inefficient. But the advantage of the heap is that the compiler does not have to know how much storage to allocate from the heap, It is also not necessary to know how long the stored data will stay in the heap, so it is much more flexible to save the data with the heap. In fact, object-oriented polymorphism, heap memory allocation is essential, because the storage space required for polymorphic variables can only be determined after the object has been created at run time. In C + +, when you want to create an object, you simply use the new command to compile the relevant code. When this code is executed, the data is automatically saved in the heap. Of course, to achieve this flexibility, there will be a cost: allocating storage space in the heap takes longer! This is what led us to say that the inefficiency of the reasons, it seems that comrade Lenin said that the advantages of people are often human shortcomings, People's shortcomings are often the advantages of people (halo ~).

3 stacks and stacks in the JVM
The JVM is a stack based virtual machine. The JVM assigns a stack to each newly created thread. That is, for a Java program, it runs through the operation of the stack. The stack saves the state of the thread in frames. The JVM does only two things on the stack: A frame-by-stack and a stack operation.
We know that a method that a thread is executing is called the current method of this thread. We may not know that the current method uses a frame called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack on the thread. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate computations, and other data. This frame here is similar to the concept of the activity record in the compiler principle.
From this allocation mechanism in Java, the stack can also be understood: stacks (stack) is the storage area that the operating system establishes for this thread when it establishes a process or a thread (a thread in an operating system that supports multithreading), and the region has an advanced feature.
Each Java application uniquely corresponds to a JVM instance, with each instance uniquely corresponding to a heap. All of the class instances or arrays that the application creates in the run are placed in this heap and are shared by all threads that apply. Unlike C + +, the allocation heap memory in Java is automatically initialized. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated in the stack, that is, allocating memory from two places when an object is created, the memory allocated in the heap actually establishes the object, and the memory allocated in the stack is just a pointer to the heap object (reference) Just.
  
   Heap and Stack in Java

Java divides memory into two types: one is stack memory and the other is heap memory.
Some of the basic types of variables and 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 memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.
Heap memory is used to store 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 object in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable for the array or object.
A reference variable is equivalent to a name that is an array or an object, and you can later use the reference variable in the stack to access the array or object in the heap.
In particular, say:
Stacks and heaps are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.
Java's heap is a run-time data area in which the object allocates 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. The heap is responsible for garbage collection, the advantage of the heap is the dynamic allocation of memory size, the lifetime does not have to tell the compiler in advance, because it is dynamically allocating memory at runtime, the Java garbage collector will automatically take away these no longer used data. The disadvantage is that the access rate is slow 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. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. There are some basic types of variables in the stack (, int, short, long, byte, float, double, Boolean, char), and object handles.
Stack has a very important particularity, is the existence of the stack of data can be shared. Let's say we both define:
int a = 3;
int b = 3;
  The compiler deals with int a = 3 First, it creates a reference to a in the stack, finds out if there is a 3 value in the stack, and if not, it stores 3 in, then points a to 3. then process int b = 3, after you create the reference variable for B, because you already have 3 in the stack, point B directly to 3. In this way, there is a case where A and B both point to 3. At this point, if you make a=4 again, the compiler will search for a 4 value in the stack, and if not, put 4 in and point A to 4, and if so, direct a to this address. Therefore the change of a value does not affect the value of B. Note that this sharing of data is different from the two-object reference to an object, because the modification of a does not affect B, it is done by the compiler, and it helps save space. While an object reference variable modifies the internal state of the object, it affects another object reference variable.

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.