现在的位置: 首页 > 综合 > 正文

Java中堆栈的提问与回答

2018年05月16日 ⁄ 综合 ⁄ 共 1313字 ⁄ 字号 评论关闭

原文链接:点击打开链接

问:

class A {
       int a ;
       String b;
       //getters and setters
}

1.变量a存储在哪里?

2.为什么堆内存会存在?为什么我们不可以将它存储在栈里?

3.gc什么时候回收对象?栈和对象销毁有联系吗?

答:

1.

堆和栈的最基本的区别是值的生命周期!


栈中的值只存在它们所被创建的函数中,一旦被返回,他将被丢弃。

堆的值存在于堆中。他们被创建于某时刻,在另一时段被摧毁(被gc或手动回收,依赖于运行环境)。


java把基本类型存储在栈中。这样可以使堆栈变小,有助于保持个人的堆栈小,从而使更多的嵌套调用。

对象被创建在堆中,其引用(这又是基本类型)存储在栈中。所以你在堆中创建对象,其包含的一些变量可以在函数被调用后持久保持。


2.

  1. In the heap, as part of the object, which is referenced by a pointer in the stack. ie. a and b will be stored adjacent to each other.
  2. Because if all memory were stack memory, it wouldn't be efficient any more. It's good to have a small, fast-access area where
    we start and have that reference items in the much larger area of memory which remains. However, this is overkill when an object is simply a single primitive which would take up about the same amount of space on the stack as the pointer to it would.
  3. Yes.

3.

  1. On the heap unless Java allocates the class instance on the stack as an optimization after proving via escape analysis that this will not affect semantics. This is an implementation detail, though, so for all practical purposes except micro-optimization the
    answer is "on the heap".

  2. Stack memory must be allocated and deallocated in last in first out order. Heap memory can be allocated and deallocated in any order.

  3. When the object is garbage collected, there are no more references pointing to it from the stack. If there were, they'd keep the object alive. Stack primitives aren't garbage collected at all because they're automatically destroyed when the function returns.


【上篇】
【下篇】

抱歉!评论已关闭.