About stack and heap in JAVA(1)

本文详细解释了计算机内存中栈和堆的区别。栈用于存放运行前声明的变量,而堆则用于运行时创建的对象。在多线程应用中,每个线程有自己的栈,但所有线程共享同一堆内存。此外还介绍了如何在Java中创建栈和堆上的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored. The heap is the section of a computer memory where all the variables created or initialized at runtime are stored.

They are both stored in the computer’s RAM(Random Access Memory).

In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap. Because the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they don’t try to access and manipulate the same piece(s) of memory in the heap at the same time.

An object can be stored on the stack. If you create an object inside a function without using the “new” operator then this will create and store the object on the stack, and not on the heap. Suppose we have a java class called member, for which we want to create an object, we also have a function called somefunction(). Here is what the code would look like:

Code to create an object on the stack:

Public void somefunction()

{

Member m;

}

So, the object “m” is destroyed once the function has run to completion. The memory being used for the object “m” on the stack will be removed once the function is done running.

If we want to create an object on the heap inside a function, then this is what the code would look like:

Public void somefunction(){

Member m=new Member();

}

Any data on the heap will remain there until gc manually reallocate them.

The stack is set to a fixed size, and cannot grow past its fixed size. So, if there is not enough room on the stack to handle the memory being assigned to it, a stack overflow occurs. This often happens when a lot of nested functions are being called, or if there is an infinite recursive call.

If the current size of the heap is too small to accommodate new memory, then more memory can be added to the heap by the operating system. This is one of the big differences between the heap and the stack.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值