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

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

问题描述

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

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