JVM 常量池、运行时常量池、字符串常量池

常量池:

  即class文件常量池,是class文件的一部分,用于保存编译时确定的数据。

保存的内容如下图:

JVM 常量池、运行时常量池、字符串常量池

  JVM 常量池、运行时常量池、字符串常量池

 D:\java\test\out\production\test>javap -verbose mainTest
Classfile /D:/java/test/out/production/test/mainTest.class
Last modified 2019年4月22日; size bytes
MD5 checksum 08699c6d713bc8967a8daea381ce23c1
Compiled from "mainTest.java"
public class mainTest
minor version:
major version:
flags: (0x0021) ACC_PUBLIC, ACC_SUPER
this_class: # // mainTest
super_class: # // java/lang/Object
interfaces: , fields: , methods: , attributes:
Constant pool:
# = Methodref #.# // java/lang/Object."<init>":()V
# = Fieldref #.# // mainTest.age2:I
# = String # // sss
# = Class # // mainTest
# = Class # // java/lang/Object
# = Utf8 age2
# = Utf8 I
# = Utf8 <init>
# = Utf8 ()V
# = Utf8 Code
# = Utf8 LineNumberTable
# = Utf8 LocalVariableTable
# = Utf8 this
# = Utf8 LmainTest;
# = Utf8 main
# = Utf8 ([Ljava/lang/String;)V
# = Utf8 args
# = Utf8 [Ljava/lang/String;
# = Utf8 name
# = Utf8 Ljava/lang/String;
# = Utf8 nick
# = Utf8 age
# = Utf8 SourceFile
# = Utf8 mainTest.java
# = NameAndType #:# // "<init>":()V
# = NameAndType #:# // age2:I
# = Utf8 sss
# = Utf8 mainTest
# = Utf8 java/lang/Object
{
public mainTest();
descriptor: ()V
flags: (0x0001) ACC_PUBLIC
Code:
stack=, locals=, args_size=
: aload_0
: invokespecial # // Method java/lang/Object."<init>":()V
: aload_0
: bipush
: putfield # // Field age2:I
: return
LineNumberTable:
line :
line :
LocalVariableTable:
Start Length Slot Name Signature
this LmainTest; public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
Code:
stack=, locals=, args_size=
: ldc # // String sss
: astore_1
: ldc # // String sss
: astore_2
: bipush
: istore_3
: return
LineNumberTable:
line :
line :
line :
line :
LocalVariableTable:
Start Length Slot Name Signature
args [Ljava/lang/String;
name Ljava/lang/String;
nick Ljava/lang/String;
age I
}
SourceFile: "mainTest.java"

运行时常量池:

  Java语言并不要求常量一定只能在编译期产生,运行期间也可能产生新的常量,这些常量被放在运行时常量池中。

  类加载后,常量池中的数据会在运行时常量池中存放

  这里所说的常量包括:基本类型包装类(包装类不管理浮点型,整形只会管理-128到127)和String(也可以通过String.intern()方法可以强制将String放入常量池)

字符串常量池:

  HotSpot VM里,记录interned string的一个全局表叫做StringTable,它本质上就是个HashSet<String>。注意它只存储对java.lang.String实例的引用,而不存储String对象的内容

jdk 1.7后,移除了方法区间,运行时常量池和字符串常量池都在堆中。

上一篇:CodeForces - 425E Sereja and Sets 题解


下一篇:iOS 面试总结 二