Java heap memory and stack memory differences

Source: Internet
Author: User

Welcome reprint. Please attach the source:
http://blog.csdn.net/as02446418/article/details/47007975

I recently in preparation for the interview time again read some Java basics, let's look at the Java stack memory differences:

Java divides the memory into two kinds. One is called stack memory. A heap of memory called

Some 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 memory space for the variable in the stack. When the scope of the variable is exceeded, Java will voluntarily release the allocated memory space for the variable, and the memory space can be used for other purposes immediately.
Heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the Java Virtual machine's own active garbage collector. Once an array or object has been created in the heap, it is also possible to define a special variable in the stack that is equal to the array or the first address of the object in the heap memory. This particular variable in the stack becomes the reference variable of an array or an object, which can then be used to access an array or an object in the heap using a reference variable in the stack memory, which is the equivalent of an alias for the arrays or objects. or code.
A reference variable is a normal variable. Allocates memory in the stack when defined. The reference variable is released in the program execution to an extraterritorial scope.

The array and the objects themselves are allocated in the heap, and the heap memory occupied by the array and the object itself is not freed, even if the program executes to a block of code that uses the new generation of arrays and objects. Arrays and objects when no reference variable points to it. It becomes rubbish and can no longer be used. However, it still occupies memory and is released by the garbage collector at a later indeterminate time. This is also the main reason why Java is more of a memory, and in fact, the variables in the stack point to the variables in the heap memory. This is the pointer in Java!

Memory allocation strategy and heap and stack comparison in Java

  1 memory allocation policy

According to the theory of compiling, there are three strategies for memory allocation in program execution, which are static, stacked, and heap-based.

Static storage allocation is the ability at compile time to determine the storage space requirements of each data target at the time of execution, so that they can be allocated a fixed amount of memory at compile time. Such an allocation policy requires that the application code does not agree with the existence of mutable data structures (such as mutable arrays), and does not agree with nested or recursive structures, Because they all cause the compiler to be unable to calculate the exact storage space requirements.

A stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like execution stack. In contrast to static storage allocation, in a stack storage scenario, the requirements for the data area are completely unknown at compile time, only to be able to know when it is executed, but when the rules are entered into a program module in execution, It is important to know that the size of the data area required by the program module is sufficient to allocate memory for it. As with the stack we are familiar with in data structures, the stack storage allocation is distributed according to the principle of advanced post-out.

Static storage allocation requires that the storage requirements of all variables be known at compile time, and that the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is specifically responsible for the memory allocation of the data structures that the storage requirements cannot be determined at compile time or at the execution of the module entrance. For example, variable-length strings and object instances. The heap consists of large chunks of available blocks or spare blocks, and the memory in the heap can be allocated and freed in random order.

  2 Comparison of heaps and stacks

The above definition is summarized in the textbook of compiling principles, except static storage allocation, it is very inflexible and difficult to understand, the following aside static storage allocation, concentrated comparison heap and stack:

From the heap and the function of the stack and the role of popular comparison, the heap is mainly used to store objects, the stack is mainly used to execute the program. And this difference is mainly due to the characteristics of the heap and stack:

In programming. For example, C + +. All of the method calls are made through stacks, all local variables, and the formal parameters are allocated from the stack of memory space. In fact, it is not a distribution, just from the top of the stack, just like a conveyor belt in the factory (conveyor belt), stack pointer will take the initiative to guide you to the location of the place, all you have to do is to put things down. When you exit the function. The stack pointer will be able to destroy the contents of the stack. This mode is the fastest, of course, to execute the program. It is important to note that when allocating a data area for a program module that is about to be called, you should know the size of the data area beforehand, even though the allocation is performed at program execution time. However, the size of the allocation is determined, unchanged, and the "size of how much" is determined at compile time, not at the time of execution.

A heap is an application that requests the operating system to allocate its own memory when it executes, and because of the memory allocations that are 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 space to allocate from the heap. It is also not necessary to know how long the stored data will stay in the heap, so there is greater flexibility in storing the data with the heap.

In fact, object-oriented polymorphism, heap memory allocation is indispensable, because the polymorphic variables required for storage space only after the execution of the object created after the ability to determine. in C + +, when you require an object to be created, you only need to compile the relevant code with the new command.

When executing the code, the data is saved on its own initiative in the heap. Of course, to achieve such flexibility, there is a certain price to pay: it will take longer to allocate storage space in the heap! This is the reason why we have just said that the efficiency is low, it seems that comrade Lenin said good, people's strengths are often human shortcomings, People's shortcomings are often also a person's strengths (halo ~).

  3 stacks and stacks in the JVM

The JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. In other words, for a Java program. Its execution is done through the operation of the stack.

The stack holds the state of the thread in frames. The JVM only performs two operations on the stack: the stacking and stacking operations in frames.

We know that the method that a thread is executing is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack of threads. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold arguments, local variables, intermediate calculations, and other data. This frame is almost identical to the concept of the activity record in the compilation principle.

From the perspective of this allocation mechanism in Java, the stack can be understood as a stack is a storage area that the operating system establishes for a process or thread (a thread in an operating system that supports multithreading). The area has advanced post-out characteristics.

Each Java application is uniquely corresponding to a JVM instance, with each instance uniquely corresponding to a heap. All instances or arrays of classes created by the application in execution are placed in the heap and shared by all threads of the application. Unlike C + +, the allocation of heap memory in Java is self-initiated. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated on 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 on the stack is just a pointer to the heap object (reference) Only.

  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 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 memory space for the variable in the stack, and when the scope of the variable is exceeded, Java will voluntarily release the allocated memory space for that variable. This memory space can be used for other purposes immediately.

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

The memory allocated in the heap. Managed by the Java Virtual machine's own active garbage collector.

After an array or an object has been generated in the heap. It is also possible to 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. This 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. You can then use reference variables from the stack in your program to access arrays or objects in the heap.

To say in detail:

Stacks and heaps are places that Java uses to store data in RAM. Unlike C + +, Java itself proactively manages stacks and heaps. Program apes cannot directly set up stacks or heaps.

  The Java heap is an execution-time data area in which the object allocates space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray. They do not require program code to be explicitly released. The heap is responsible for garbage collection, and the heap has the advantage of being able to dynamically allocate memory size. The lifetime also does not have to tell the compiler beforehand, because it is dynamically allocating memory at execution time. Java's garbage collector will voluntarily take away 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 execution 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 the existence of data in the stack can be shared. Suppose we define at the same time:

 int3;   int3

The compiler processes int a = 3 First, it creates a reference to the variable A in the stack, and then finds out if there is a value of 3 in the stack, assuming that it is not found, 3 is stored in. Then point A to 3. then the int b = 3 is processed, and after the reference variable of B is created, the value of 3 is already in the stack. Point B directly to 3. In this case, A and B are all pointing to 3 at the same time. At this point, suppose again to make a=4, then the compiler will search the stack again if there are 4 values, if not, then 4 is stored in, and a point to 4; if already, then direct a to the address. Therefore the change of a value does not affect the value of B. It is important to note that such a share of the data is different from the two-object reference at the same time pointing to an object, because the change of a does not affect B, it is completed by the compiler, and it facilitates space saving. An object reference variable changes the internal state of the object, affecting the addition of an object reference variable

Java heap memory and stack memory differences

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.