Memory heap and stack

All objects are stored on the heap (including their attributes).1

Local variables (including arguments) always contain primitive values or references and are stored on the stack.

String one = "abc";
String two = new String("abc");
You'll have two objects on the heap (two String objects containing "abc") and two references, one for each object, on the stack (provided one and two are local variables).

There are two storage areas involved: the stack and the heap. The stack is where the current stateof a method call is kept (ie local variables and references), and the heap is where objects are stored. The Hotspot documentation says that on Linux 64-bit each thread has a stack of 1024kB by default. The heap can be made arbitrary big, and today it's in the order of GB.
A recursive method uses both the stack and the heap. Which one you run out of first depends on the implementation. As an example, consider a method which needs thousands of integers: if they are declared as local variables, ie:
public void stackOverflow() { int a_1; int a_2; int a_3; // ... int a_10_000_000;}

your program will crask with a StackOverflowError
. On the other hand, if you organize your integers in an array, like:
public void outOfMemory() { int[] integers = new int[10 * 1000 * 1000];}

the heap will be filled soon, and the program will end with an OutOfMemoryError
. In neither case the memory is corrupted or data overridden. However, in both cases the code is wrong and must be fixed somehow - but to tell you how we'd need to know more about your program.

Deque (Stack) as object is stored on the heap

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 好久没有翻看QQ上的好友动态,今天随意浏览了那么几页。一个个萌娃照浮现,顿时嫉妒心起,偶又在脑海中把那个不知在哪儿...
    鱼琪儿阅读 212评论 0 1
  • 野水笑谈录 (一) 二十多年前。 离城八十里有个乡,叫野水乡。乡里有所中学,叫野水乡中。野水乡中的校长姓吴名虚,四...
    独行的老雕虫阅读 469评论 0 3
  • 在刚刚送走的2016年,我决定从年初就开始写日记,而且要坚持一年。现在一年过去了,除了6、7月没有天天记,其他时间...
    奔跑的马齿苋阅读 154评论 0 0