JVM——方法区

1. 什么是方法区

方法区,也称非堆(Non-Heap),是一个被线程共享的内存区域

其中主要存储加载的类字节码、class/method/field等元数据对象、static-final常量、static变量、jit编译器编译后的代码缓存等数据。另外,方法区包含了一个特殊的区域“运行时常量池”。

方法区包含:

  • 类信息:修饰符(public、abstract、final)、全类名、接口列表、父类全类名
  • 域(Field,即方法中成员变量)信息:域名称、域类型、域修饰符:private int num;
  • 方法信息:方法名称、返回类型、参数名称及类型、异常信息等:public void delete (String path) throws IOException{ }
  • 运行时常量池:字面值(比如字符串值)、符号引用
  • 静态变量(static、非final):静态变量会在类加载时,赋初始值;final变量(常量)在编译期就被确定,放在运行时常量池中
  • 对类加载器的引用
  • 对Class类的引用
  • 方法表

2. 永久代与元空间

方法区是JVM的规范,永久代与元空间是HotSpot JVM两种落地实现方式。 jdk1.7通过永久代实现,jdk1.8通过元空间实现

  • PermGen Space(永久代)

永久代指的是永久保存区域,逻辑上属于堆空间。主要存放Class和Meta(元数据)的信息。Classic在被加载的时候被放入永久代。

  • MetaSpace(元空间)

元空间和永久代类似,都是对JVM规范中方法的实现。不过元空间并不在虚拟机中,而是使用本地内存。默认情况下,元空间的大小仅受本地内存的限制。类的元数据放入native memory,字符串池和类的静态变量放入java堆中。

-XX:MetaspaceSize ,初始空间大小
-XX:MaxMetaspaceSize,最大空间
  • 采用元空间而不用永久代的原因
    • 元数据(比如字符串)和class对象存放在永久代中,容易出现性能问题和内存溢出
    • 类及方法的信息等比较难确定其大小,因此对于永久代大小指定比较困难,大小容易出现永久代溢出,太大容易导致老年代溢出(堆内存不变,此消彼长)
    • 永久代会为GC带来不必要的复杂度,并且回收效率偏低
版本变化
jdk1.6有永久代,静态变量存放在永久代上
jdk1.7有永久代,但已逐步“去永久代”,字符串常量池、静态变量从永久代中移除,存放在堆中
jdk1.8无永久代,类型信息、字段、方法、常量保存在本地内存的元空间,但字符串常量池、静态变量保存在堆中

3. 常量池与运行时常量池

以上述字节码文件为例

public void test1() {
	int count =20;
	System.out.println("count="+count);
}

编译得到字节码文件

 0 bipush 20
 2 istore_1
 3 getstatic #3 <java/lang/System.out>
 6 new #4 <java/lang/StringBuilder>
 9 dup
10 invokespecial #5 <java/lang/StringBuilder.<init>>
13 ldc #6 <count=>
15 invokevirtual #7 <java/lang/StringBuilder.append>
18 iload_1
19 invokevirtual #8 <java/lang/StringBuilder.append>
22 invokevirtual #9 <java/lang/StringBuilder.toString>
25 invokevirtual #10 <java/io/PrintStream.println>
28 return

以其中第3行为例:调用 #3 <java/lang/System.out>,查看字节码文件中的常量池

/* Fieldref:指向字段的符号引用 */
 #3 = Fieldref           #44.#45        // java/lang/System.out:Ljava/io/PrintStream;
/* Class:指向类(包括数组类、枚举类)和接口的符号引用 */
#44 = Class              #63            // java/lang/System
/* NameAndType:给出字段或方法的名称和描述符 */
#45 = NameAndType        #64:#65        // out:Ljava/io/PrintStream;
/* Utf8:存放MUTF-8编码的字符串 */
#63 = Utf8               java/lang/System
#64 = Utf8               out
#65 = Utf8               Ljava/io/PrintStream;

第6行:new #4 <java/lang/StringBuilder>

 #4 = Class              #46            // java/lang/StringBuilder
#46 = Utf8               java/lang/StringBuilder

第10行:invokespecial #5 <java/lang/StringBuilder.>

 #5 = Methodref          #4.#42         // java/lang/StringBuilder."<init>":()V
 #4 = Class              #46            // java/lang/StringBuilder  
#42 = NameAndType        #25:#26        // "<init>":()V
#46 = Utf8               java/lang/StringBuilder
#25 = Utf8               <init>
#26 = Utf8               ()V

所以,常量池中至少包含:

  • 字符串值:#6 = String #47 // count=
  • 字段的符号引用:#3 = Fieldref #44.#45 // java/lang/System.out:Ljava/io/PrintStream;
  • 类的符号引用:#44 = Class #63 // java/lang/System
  • 方法的符号引用:#45 = NameAndType #64:#65
  • 等其他信息,可参考:常量池中存储的数据类型

什么是运行时常量池?

  • 常量池是Class文件中的一部分,用于存储编译器生成的各种字面量与符号引用
  • 常量池中内容经过Class Loader过程存放到方法区中的运行时常量池
  • 相比常量池,具有动态性

4. 方法区垃圾回收

主要回收:

  • 废弃的常量
  • 不再使用的类型(判断起来很麻烦)
    • 该类所有的实例被回收
    • 加载该类的加载器被回收
    • 该类不被引用,无法通过反射访问该类的方法

5. 示例

  • 使用字节码文件分析方法区
public class TestMethodArea extends Object implements Comparable<String>,Serializable{
	//属性
	public int num=10;
	private static String s="测试方法区内部结构";
	
	//构造器,使用默认的
	
	//自定义方法
	public void test1() {
		int count =20;
		System.out.println("count="+count);
	}
	public static int test2(int cal) {
		int res=0;
		try {
			int val=20;
			res=val/cal;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	//继承接口重写的方法
	@Override
	public int compareTo(String o) {
		return 0;
	}

}
  • 编译:javac TestMethodArea.java
  • 反编译:javap -v -p TestMethodArea.class > test1.txt
  • 打开test1.txt
Classfile /C:/Users/cc/Desktop/TestMethodArea.class
  Last modified 2020-8-3; size 1338 bytes
  MD5 checksum 6deebe9989d830f376c1755cb0562380
  Compiled from "TestMethodArea.java"
//方法信息
public class com.cc.methodarea.TestMethodArea extends java.lang.Object implements java.lang.Comparable<java.lang.String>, java.io.Serializable
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
//常量池
Constant pool:
   #1 = Methodref          #18.#42        // java/lang/Object."<init>":()V
   #2 = Fieldref           #17.#43        // com/cc/methodarea/TestMethodArea.num:I
   #3 = Fieldref           #44.#45        // java/lang/System.out:Ljava/io/PrintStream;
   #4 = Class              #46            // java/lang/StringBuilder
   #5 = Methodref          #4.#42         // java/lang/StringBuilder."<init>":()V
   #6 = String             #47            // count=
   #7 = Methodref          #4.#48         // java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   #8 = Methodref          #4.#49         // java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   #9 = Methodref          #4.#50         // java/lang/StringBuilder.toString:()Ljava/lang/String;
  #10 = Methodref          #51.#52        // java/io/PrintStream.println:(Ljava/lang/String;)V
  #11 = Class              #53            // java/lang/Exception
  #12 = Methodref          #11.#54        // java/lang/Exception.printStackTrace:()V
  #13 = Class              #55            // java/lang/String
  #14 = Methodref          #17.#56        // com/cc/methodarea/TestMethodArea.compareTo:(Ljava/lang/String;)I
  #15 = String             #57            // 测试方法区内部结构
  #16 = Fieldref           #17.#58        // com/cc/methodarea/TestMethodArea.s:Ljava/lang/String;
  #17 = Class              #59            // com/cc/methodarea/TestMethodArea
  #18 = Class              #60            // java/lang/Object
  #19 = Class              #61            // java/lang/Comparable
  #20 = Class              #62            // java/io/Serializable
  #21 = Utf8               num
  #22 = Utf8               I
  #23 = Utf8               s
  #24 = Utf8               Ljava/lang/String;
  #25 = Utf8               <init>
  #26 = Utf8               ()V
  #27 = Utf8               Code
  #28 = Utf8               LineNumberTable
  #29 = Utf8               test1
  #30 = Utf8               test2
  #31 = Utf8               (I)I
  #32 = Utf8               StackMapTable
  #33 = Class              #53            // java/lang/Exception
  #34 = Utf8               compareTo
  #35 = Utf8               (Ljava/lang/String;)I
  #36 = Utf8               (Ljava/lang/Object;)I
  #37 = Utf8               <clinit>
  #38 = Utf8               Signature
  #39 = Utf8               Ljava/lang/Object;Ljava/lang/Comparable<Ljava/lang/String;>;Ljava/io/Serializable;
  #40 = Utf8               SourceFile
  #41 = Utf8               TestMethodArea.java
  #42 = NameAndType        #25:#26        // "<init>":()V
  #43 = NameAndType        #21:#22        // num:I
  #44 = Class              #63            // java/lang/System
  #45 = NameAndType        #64:#65        // out:Ljava/io/PrintStream;
  #46 = Utf8               java/lang/StringBuilder
  #47 = Utf8               count=
  #48 = NameAndType        #66:#67        // append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  #49 = NameAndType        #66:#68        // append:(I)Ljava/lang/StringBuilder;
  #50 = NameAndType        #69:#70        // toString:()Ljava/lang/String;
  #51 = Class              #71            // java/io/PrintStream
  #52 = NameAndType        #72:#73        // println:(Ljava/lang/String;)V
  #53 = Utf8               java/lang/Exception
  #54 = NameAndType        #74:#26        // printStackTrace:()V
  #55 = Utf8               java/lang/String
  #56 = NameAndType        #34:#35        // compareTo:(Ljava/lang/String;)I
  #57 = Utf8               测试方法区内部结构
  #58 = NameAndType        #23:#24        // s:Ljava/lang/String;
  #59 = Utf8               com/cc/methodarea/TestMethodArea
  #60 = Utf8               java/lang/Object
  #61 = Utf8               java/lang/Comparable
  #62 = Utf8               java/io/Serializable
  #63 = Utf8               java/lang/System
  #64 = Utf8               out
  #65 = Utf8               Ljava/io/PrintStream;
  #66 = Utf8               append
  #67 = Utf8               (Ljava/lang/String;)Ljava/lang/StringBuilder;
  #68 = Utf8               (I)Ljava/lang/StringBuilder;
  #69 = Utf8               toString
  #70 = Utf8               ()Ljava/lang/String;
  #71 = Utf8               java/io/PrintStream
  #72 = Utf8               println
  #73 = Utf8               (Ljava/lang/String;)V
  #74 = Utf8               printStackTrace
{
  //域信息
  public int num;
    descriptor: I
    flags: ACC_PUBLIC

  private static java.lang.String s;
    descriptor: Ljava/lang/String;
    flags: ACC_PRIVATE, ACC_STATIC

  //默认构造器 init方法
  public com.cc.methodarea.TestMethodArea();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        10
         7: putfield      #2                  // Field num:I
        10: return
      LineNumberTable:
        line 5: 0
        line 7: 4

  //方法信息
  public void test1();
    descriptor: ()V
    flags: ACC_PUBLIC
    //字节码
    Code:
      //操作数栈、局部变量表、参数大小(指this对象)
      stack=3, locals=2, args_size=1
         0: bipush        20
         2: istore_1
         3: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
         6: new           #4                  // class java/lang/StringBuilder
         9: dup
        10: invokespecial #5                  // Method java/lang/StringBuilder."<init>":()V
        13: ldc           #6                  // String count=
        15: invokevirtual #7                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        18: iload_1
        19: invokevirtual #8                  // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
        22: invokevirtual #9                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
        25: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        28: return
      LineNumberTable:
        line 14: 0
        line 15: 3
        line 16: 28

  public static int test2(int);
    descriptor: (I)I
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=3, args_size=1(指int形参、static没有this类型)
         0: iconst_0
         1: istore_1
         2: bipush        20
         4: istore_2
         5: iload_2
         6: iload_0
         7: idiv
         8: istore_1
         9: goto          17
        12: astore_2
        13: aload_2
        14: invokevirtual #12                 // Method java/lang/Exception.printStackTrace:()V
        17: iload_1
        18: ireturn
      //异常表
      Exception table:
         from    to  target type
             2     9    12   Class java/lang/Exception
      LineNumberTable:
        line 18: 0
        line 20: 2
        line 21: 5
        line 24: 9
        line 22: 12
        line 23: 13
        line 25: 17
      StackMapTable: number_of_entries = 2
        frame_type = 255 /* full_frame */
          offset_delta = 12
          locals = [ int, int ]
          stack = [ class java/lang/Exception ]
        frame_type = 4 /* same */

  public int compareTo(java.lang.String);
    descriptor: (Ljava/lang/String;)I
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=2
         0: iconst_0
         1: ireturn
      LineNumberTable:
        line 31: 0

  public int compareTo(java.lang.Object);
    descriptor: (Ljava/lang/Object;)I
    flags: ACC_PUBLIC, ACC_BRIDGE, ACC_SYNTHETIC
    Code:
      stack=2, locals=2, args_size=2
         0: aload_0
         1: aload_1
         2: checkcast     #13                 // class java/lang/String
         5: invokevirtual #14                 // Method compareTo:(Ljava/lang/String;)I
         8: ireturn
      LineNumberTable:
        line 5: 0

  static {};
    descriptor: ()V
    flags: ACC_STATIC
    Code:
      stack=1, locals=0, args_size=0
         0: ldc           #15                 // String 测试方法区内部结构
         2: putstatic     #16                 // Field s:Ljava/lang/String;
         5: return
      LineNumberTable:
        line 8: 0
}
Signature: #39                          // Ljava/lang/Object;Ljava/lang/Comparable<Ljava/lang/String;>;Ljava/io/Serializable;
SourceFile: "TestMethodArea.java"
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页