Java Heap Memory

Heap memory is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.
Stack memory size is very less compared to Heap memory.

Let’s understand the Heap and Stack memory usage with a simple program.

package com.journaldev.test;

public class Memory {

    public static void main(String[] args) { // Line 1
int i=1; // Line 2
Object obj = new Object(); // Line 3
Memory mem = new Memory(); // Line 4
mem.foo(obj); // Line 5
} // Line 9 private void foo(Object param) { // Line 6
String str = param.toString(); //// Line 7
System.out.println(str);
} // Line 8 }

Below image shows the Stack and Heap memory with reference to above program and how they are being used to store primitive, Objects and reference variables.

Let’s go through the steps of execution of the program.

  • As soon as we run the program, it loads all the Runtime classes into the Heap space. When main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
  • We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
  • Since we are creating an Object in line 3, it’s created in Heap memory and stack memory contains the reference for it. Similar process occurs when we create Memory object in line 4.
  • Now when we call foo() method in line 5, a block in the top of the stack is created to be used by foo() method. Since Java is pass by value, a new reference to Object is created in the foo() stack block in line 6.
  • A string is created in line 7, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
  • foo() method is terminated in line 8, at this time memory block allocated for foo() in stack becomes free.
  • In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also the program ends at this line, hence Java Runtime frees all the memory and end the execution of the program.

Difference between Heap and Stack Memory

Based on the above explanations, we can easily conclude following differences between Heap and Stack memory.

  1. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  2. Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  3. Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
  4. Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
  5. Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
  6. We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
  7. When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  8. Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

That’s all for Stack vs Heap Memory in terms of java application, I hope it will clear your doubts regarding memory allocation when any java program is executed.

原作者:Pankaj

好文分享_java堆栈的区别的更多相关文章

  1. java中堆和堆栈的区别

    java中堆和堆栈的区别(一) 1.栈(stack)与堆(heap)都是Java用来在Ram中存放数据的地方.与C++不同,Java自动管理栈和堆,程序员不能直接地设置栈或堆. 2. 栈的优势是,存取 ...

  2. 趣文分享:有人将Android开发环境比作女人

    (一个移动开发者大会活动推荐:http://www.eoeandroid.com/thread-303943-1-1.html) 趣文分享:有人将Android开发环境比作女人 在日常开发工作中,我们 ...

  3. 趣文分享:C 语言和 C++、C# 的区别在什么地方?

    任务: 把大象放到冰箱里.

  4. C#·好文分享

    时间:2018-11-14 记录:byzqy 好文收藏,集中分享! 标题:C#接口<通俗解释> 地址:https://www.cnblogs.com/hamburger/p/4681681 ...

  5. C语言堆栈的区别

    堆(heap)和栈(stack)有什么区别?? 简单的可以理解为: heap:是由malloc之类函数分配的空间所在地.地址是由低向高增长的. astack:是自动分配变量,以及函数调用的时候所使用的 ...

  6. 【校招面试 之 C/C++】第14题 C++ 内存分配方式详解——堆、栈、自由存储区、全局/静态存储区和常量存储区(堆栈的区别)

    栈,就是那些由编译器在需要的时候分配,在不需要的时候自动清除的变量的存储区.里面的变量通常是局部变量.函数参数等.在一个进程中,位于用户虚拟地址空间顶部的是用户栈,编译器用它来实现函数的调用.和堆一样 ...

  7. c++中关于堆和堆栈的区别

    在C++中,内存分成5个区,他们分别是堆.栈.自由存储区.全局/静态存储区和常量存储区.       栈,就是那些由编译器在需要的时候分配,在不需要的时候自动清楚的变量 的存储区.里面的变量通常是局部 ...

  8. <JavaScript>“浏览器模式”和“文档模式”之间的区别

    只有IE浏览器中才会有“浏览器模式”和“文档模式”,兼容性视图涉及两个重要的功能便是“浏览器模式[browser mode]”和“文档模式[document mode]”,在IE8/IE9中按F12键 ...

  9. 【好文分享】为什么强烈禁止开发人员使用isSuccess作为变量名

    原文来自阿里云hollies:https://developer.aliyun.com/article/701413   简介: 在日常开发中,我们会经常要在类中定义布尔类型的变量,比如在给外部系统提 ...

随机推荐

  1. 输出 Office 报表

    以 word 为例: 将 word 存为 Word2003 XML,其中苹果等部分即是 xml 如下: 服务器端通常输出 HTML,HTML 是文本,XML也是文本,可以简单的套用服务器端网页的思路. ...

  2. 深入理解jsonp跨域请求原理

    在进行网站开发的过程中经常会用到第三方的数据,但是由于同源策略的限制导致ajax不能发送请求,因此也无法获得数据.解决ajax的跨域问题有两种方法: 一.jsop 二.XMLHttpRequest2中 ...

  3. Java类的加载の动态

    类的加载方式 静态加载类,是编译时刻加载 动态加载类,是运行时刻加载 new创建对象:是静态加载类,在编译时刻就需要加载所有的可能使用到的类.有一个类有问题(如不存在),都不能通过编译,会报错. Cl ...

  4. Backbone源码学习之extend

    extend函数在backbone大概就20来行代码包括注释,对学习Javascript中"类"的继承很是好的学习资料. 下面先贴出Backbone中的源码,其中涉及到unders ...

  5. Linux sort 命令

    - 今天的收获: sort -t $'\t' 说明:sort 加-t 参数时,如果需要以 '\t' 分隔,需要写成上述形式.

  6. 自己常用的webstrom快捷键

    1.ctrl+"d" 复制正行 2.ctrl+"y" 删除正行 3.ctrl+"-" 缩小整块 4.ctrl+"+" 扩 ...

  7. MySQL · 答疑解惑 · MySQL 锁问题最佳实践

    http://mysql.taobao.org/monthly/2016/03/10/ 前言 最近一段时间处理了较多锁的问题,包括锁等待导致业务连接堆积或超时,死锁导致业务失败等,这类问题对业务可能会 ...

  8. HTML DOM Event 对象

    var event;if (document.createEvent){event = document.createEvent("HTMLEvents");event.initE ...

  9. MVC4中基于bootstrap和HTML5的图片上传Jquery自定义控件

    场景:mvc4中上传图片,批量上传,上传前浏览,操作.图片进度条. 解决:自定义jquery控件 没有解决:非图片上传时,会有浏览样式的问题; 解决方案; 1.样式 – bootstrap 的css和 ...

  10. 如何正确的做WEB端的压力测试

    1.对要测试的系统进行分析,明确需要对哪一块做压力测试.比如:淘宝网站双十一期间,秒杀跟支付,此模式用户操作中占比比较大 再比如:游戏,登录--开始战斗--结束战斗这种混合模式在用户操作中占比较大 那 ...