Home> Java> JavaBase> body text

What is the difference between stack memory and heap memory in Java?

王林
Release: 2020-05-17 15:21:51
Original
4656 people have browsed it

What is the difference between stack memory and heap memory in Java?

The difference between stack memory and heap memory:

1. Stack memory is used to store basic types of variables and reference variables, and heap memory is used to store basic types of variables and reference variables. 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.

(Video tutorial recommendation:java video)

2. The stack memory belongs to a single thread. Each thread will have a stack memory, and the variables it stores can only It is visible in the thread to which it belongs, that is, the stack memory can be understood as the private memory of the thread; the objects in the heap memory are visible to all threads. Objects in heap memory can be accessed by all threads.

3. If there is no available space in the stack memory to store method calls and local variables, the JVM will throw the java.lang.stackoverflowerror error; if there is available space in the heap memory to store the generated objects, the JVM will throw A java.lang.outofmemoryerror error occurred.

3. The stack memory is much smaller than the heap memory. If you use recursion, your stack will fill up quickly. -Xss sets the size of each thread's stack memory -Xms can set the size of the heap memory at the beginning.

Summary:

The heap and stack in JVM belong to different memory areas and are used for different purposes. The stack is often used to store method frames and local variables, while objects are always allocated on the heap. The stack is usually smaller than the heap and is not shared among multiple threads, whereas the heap is shared by all threads in the entire JVM.

Recommended tutorial:Getting started with java development

The above is the detailed content of What is the difference between stack memory and heap memory in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!