Where does Java#39;s String constant pool live, the heap or the stack?(Java 的字符串常量池在哪里,堆还是栈?)
问题描述
我知道常量池和 JVM 用来处理字符串字面量的字符串常量池的概念.但我不知道 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 的字符串常量池在哪里,堆还是栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 的字符串常量池在哪里,堆还是栈?
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01