我知道常量池和 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 的字符串常量池在哪里,堆还是栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!