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 的字符串常量池在哪里,堆还是栈?
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
