Java Heap and stack comparison

Source: Internet
Author: User

When we first approached heaps and stacks, many people didn't understand why they had to set these two concepts in Java. What is the difference between heap and stack, and what are the characteristics of each? There is a data structure in Java that is in the order of a LIFO (last in First out), which is java.util.Stack. In this case, it inevitably makes many people more puzzled by the previous question. In fact, the heap and stack are all part of the memory, have different functions, and a program needs to allocate memory on this area. As we all know, all Java programs run inside the JVM virtual machine, and what we are describing here is naturally the heap and stack in the JVM (virtual) memory.

difference

The difference between heap and stack in Java is naturally a common problem in the interview, the following points are the specific differences

Duties

The main difference is that the stack memory is used to store local variables and reference instances, with advanced features.
Heap memory is used to store objects in Java. Whether they are member variables, local variables, or class variables, the objects they point to are stored in heap memory, with FIFO features.

Exclusive OR shared

Stack memory belongs to a single thread, each thread will have a stack of memory, its stored variables can only be seen in its own thread, that is, stack memory can be understood as a thread of private memory.
Objects in the heap memory are visible to all threads. Objects in the heap memory can be accessed by all threads.

exception Error

If the stack memory does not have space to store method calls and local variables, the JVM throws Java.lang.StackOverFlowError.
And if the heap memory does not have space available to store the generated objects, the JVM throws Java.lang.OutOfMemoryError.

Space Size

The memory of the stack is much smaller than the heap memory, and if you use recursion, your stack will soon be filled. If recursion does not jump out in time, stackoverflowerror problem is likely to occur.
You can set the stack memory size with the-XSS option. The-XMS option sets the size at which the heap starts, and the-XMX option sets the maximum value for the heap.

This is the difference between heap and Stack in Java. Understanding this problem can help you solve problems in development, analyze heap memory and stack memory usage, and even performance tuning.

View default values (Updated)

View the heap defaults, using the following code, where Initialheapsize is the size of the first heap, and maxheapsize is the maximum value of the heap.

 13:17 $ java-xx:+printflagsfinal-version |  grep heapsize uintx ergoheapsizelimit  = 0 {product} uintx heapsizepergcthread  = 87241 520 {product} Uintx initialheapsize:                /span>= 134217728 {product} Uintx Largepageheapsizethreshold                               = 134217728 {product} Uintx maxheapsize :  = 2147483648 {Product}java version /span> "1.8.0_25" java (TM) SE Runtime Environment (build  1.8.0_25-b17) Java HotSpot (TM)  64-bit Server VM (build 25.25-b02, mixed mode) 

View the default value of the stack, where threadstacksize is the size of the stack memory.

13:21 $ java-xx:+printflagsfinal-version | grep threadstacksize     intx compilerthreadstacksize                   = 0                                   {PD product}     Intx Threadstacksize                           = 1024x768                                {PD product}     intx vmthreadstacksize                         = 1024x768                                  "1.8.0_25"1.8.0_25-64-bit Server VM (build 25.25-b02, Mixed mode)

Summarize:

the memory mechanism of Java :

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

Some basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function, and 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 frees the memory space allocated for that variable. The memory space can be used immediately by another.

Heap memory is used to store the objects and arrays created by new, and the memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine. After creating 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. The reference variable in the stack can then be used in the program to access an array or an object in the heap, which is equivalent to a name that is an array or an object. A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope. While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed when the program runs beyond the block of code that uses new to produce the array or object's statement, and the array and object become garbage when no reference variable points to it, not in use, but still occupy memory space. The garbage collector takes off (releases) at a later indeterminate time.

This is the reason why Java compares memory, in fact, the variables in the stack point to the variables in the heap memory, this is the pointer in Java!

The allocation of variables in memory in Java:

1. class variable (static modified variable): When the program loads, the system opens up memory in the heap, and the memory address in the heap is stored on the stack for high-speed access. The life cycle of a static variable--continues until the entire system shuts down

2, instance variables : When you use the Java keyword New, the system in the heap is not necessarily a continuous space allocated to variables (such as class instances), and then based on the scattered heap memory address, the hash algorithm is converted to a long series of numbers to characterize the variable in the heap "physical location." Life cycle of instance variables-when a reference to an instance variable is lost, it is included in the recyclable "list" by the GC (garbage collector), but the memory in the heap is not released immediately

3, Local variables : Local variables, by declaring in a method, or a code snippet (such as a For loop), execution to it in the stack to open up memory, when the local variable one but out of scope, memory immediately released

Java Heap and stack comparison

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.