Java的String常量池在哪里存在,堆还是堆栈? [英] Where does Java's String constant pool live, the heap or the stack?

查看:548
本文介绍了Java的String常量池在哪里存在,堆还是堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道常量池的概念和JVM用于处理String文字的String常量池。但我不知道JVM使用哪种类型的内存来存储String常量文字。堆栈还是堆?由于它是一个与任何实例无关的文字,我会认为它将存储在堆栈中。但是如果它没有被任何实例引用,则必须通过GC运行收集文字(如果我错了就纠正我),那么如果它存储在堆栈中怎么处理呢?

I know the concept of a constants pool and the String constant pool used by JVMs to handle String literals. But I don't know which type of memory is used by the JVM to store String constant literals. The stack or the heap? Since its a literal which is not associated with any instance I would assume that it will be stored in stack. But if it's not referred by any instance the literal has to be collected by GC run (correct me if I am wrong), so how is that handled if it is stored in the stack?

推荐答案

答案在技术上都不是。根据Java虚拟机规范,存储字符串文字的区域位于运行时常量池。运行时常量池内存区域是基于每个类或每个接口分配的,因此它根本不依赖于任何对象实例。运行时常量池是方法区域的子集,它存储每类结构,例如运行时常量池,字段和方法数据,以及方法和构造函数的代码,包括使用的特殊方法在类和实例初始化和接口类型初始化。 VM规范说虽然方法区域在逻辑上是堆的一部分,但它并没有规定在方法区域中分配的内存会受到垃圾收集或与普通数据相关的其他行为的影响。分配给堆的结构。

The answer is technically neither. According to the Java Virtual Machine Specification, the area for storing string literals is in the runtime constant pool. The runtime constant pool memory area is allocated on a per-class or per-interface basis, so it's not tied to any object instances at all. The runtime constant pool is a subset of the method area which "stores per-class structures such as the runtime constant pool, field and method data, and the code for methods and constructors, including the special methods used in class and instance initialization and interface type initialization". The VM spec says that although the method area is logically part of the heap, it doesn't dictate that memory allocated in the method area be subject to garbage collection or other behaviors that would be associated with normal data structures allocated to the heap.

这篇关于Java的String常量池在哪里存在,堆还是堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆