Program Counter Register 程序计数器(寄存器):物理上是通过寄存器实现的。寄存器是CPU组件中读取数据最快的一个单元,又因为读取指令地址这个动作是非常频繁的,所以JVM把寄存器当作程序计数器
Java Virtual Machine Stacks (Java 虚拟机栈)
虚拟机栈 :每个线程运行时所需要的内存空间
栈帧:每个方法运行时需要的内存
垃圾回收是否涉及栈内存?
不需要。因为栈帧内存在每次方法结束后会被弹出栈,即被自动回收掉
栈内存分配越大越好吗?
不是。栈内存越大,只能运行更多次的递归方法调用,而不会提高运行效率。反而导致允许的线程数越少,因为物理内存是固定的。
方法内的局部变量是否线程安全?
不一定
情况一:如果方法内局部变量没有逃离方法的作用访问,它是线程安全的
情况二:如果局部变量引用了对象(方法参数)、或逃离方法的作用范围(作为返回值),需要考虑线程安全
栈帧过多导致栈内存溢出:
递归调用没有正确的结束条件
public class StackOverFlow {
private static int count=0;
public static void main(String[] args) {
try {
test();
} catch (Throwable e) {
e.printStackTrace(); //java.lang.StackOverflowError
System.out.println(count); //23010 ——> -Xss256k ——> 3639
}
}
public static void test(){
count++;
test();
}
}
递归Josn转换循环依赖:@JsonIgnore
栈帧过大导致栈内存溢出
案例1: cpu 占用过高
定位进程:top
定位线程:ps H -eo pid,tid,%cpu | grep 进程id
定位线程代码:jstack 进程id
根据线程id (换算为16进制)找到有问题的线程,进一步定位到问题代码的源码行号
案例2:产生死锁,程序运行很长时间没有结果。nohup java cn.itcast.jvm.t1.Demo1_3 &
Heap 堆
public class OutOfMemoryTest {
public static void main(String[] args) {
try {
List<String> list =new ArrayList<>();
String str="hello";
int count=0;
while (true){
str+=str; //java.lang.OutOfMemoryError: Java heap space
list.add(str);
count++;
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
案例1:创建对象前—>创建对象后—>回收对象后
public class JconsoleTest {
public static void main(String[] args) throws InterruptedException {
System.out.println("创建对象前");
Thread.sleep(20000);
byte[] array=new byte[1024*1024*10];
System.out.println("创建对象后");
Thread.sleep(10000);
array=null;
System.gc();
System.out.println("垃圾回收后");
Thread.sleep(30000);
}
}
#创建对象前:可用 27.9m
PS F:\software\IDEA\JavaProjects\JvmTest> jps
12832 RemoteMavenServer36
13264 Launcher
19044 Jps
15960
13564 JconsoleTest
PS F:\software\IDEA\JavaProjects\JvmTest> jmap -heap 13564
...
Eden Space:
capacity = 34078720 (32.5MB)
used = 4771328 (4.55029296875MB)
free = 29307392 (27.94970703125MB)
14.000901442307692% used
#创建对象后:可用 17.9m
PS F:\software\IDEA\JavaProjects\JvmTest> jmap -heap 13564
...
Eden Space:
capacity = 34078720 (32.5MB)
used = 15257104 (14.550308227539062MB)
free = 18821616 (17.949691772460938MB)
44.77017916165865% used
#垃圾回收后:可用 31.8m
PS F:\software\IDEA\JavaProjects\JvmTest> jmap -heap 13564
...
Eden Space:
capacity = 34078720 (32.5MB)
used = 681592 (0.6500167846679688MB)
free = 33397128 (31.84998321533203MB)
2.0000516451322117% used
PS F:\software\IDEA\JavaProjects\JvmTest> jconsole
案例2:垃圾回收后,内存占用仍然很高
public class JvitualvmTest {
public static void main(String[] args) throws InterruptedException {
List<Studnet> list=new ArrayList();
for (int i = 0; i < 200; i++) {
list.add(new Studnet());
}
Thread.sleep(1000000000000L);
}
}
class Studnet{
private byte[] big=new byte[1024*1024];
}
PS F:\software\IDEA\JavaProjects\JvmTest> jconsole
PS F:\software\IDEA\JavaProjects\JvmTest> jvisualvm
方法区的位置
字符串常量池的位置:
场景
1.8 以前:导致永久代内存溢出
public class OutOfMemoryTest extends ClassLoader{
public static void main(String[] args) {
int j=0;
try {
OutOfMemoryTest classLoader=new OutOfMemoryTest();
for (int i = 0; i < 100000; i++,j++) {
//作用:生成类且获得类的二进制字节码
ClassWriter cw=new ClassWriter(0);
//版本号,public,类名,包名,父类,接口
cw.visit(Opcodes.V1_6,Opcodes.ACC_PUBLIC,"Class"+i,null,"java/lang/Object",null);
//获得类的字节数组
byte[] code=cw.toByteArray();
//将该类加载到方法区
classLoader.defineClass("Class"+i,code,0,code.length);
}
} finally{
System.out.println(j);
}
}
}
19317
Exception in thread "main" java.lang.OutOfMemoryError: PermGen space
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.lang.ClassLoader.defineClass(ClassLoader.java:465)
at org.example.java.methodArea.OutOfMemoryTest.main(OutOfMemoryTest.java from InputFileObject:24)
1.8 之后:导致元空间内存溢出
public class OutOfMemoryTest extends ClassLoader{
public static void main(String[] args) {
int j=0;
try {
OutOfMemoryTest classLoader=new OutOfMemoryTest();
for (int i = 0; i < 100000; i++,j++) {
//作用:生成类且获得类的二进制字节码
ClassWriter cw=new ClassWriter(0);
//版本号,public,类名,包名,父类,接口
cw.visit(Opcodes.V1_8,Opcodes.ACC_PUBLIC,"Class"+i,null,"java/lang/Object",null);
//获得类的字节数组
byte[] code=cw.toByteArray();
//将该类加载到方法区
classLoader.defineClass("Class"+i,code,0,code.length);
}
} catch (Throwable t){
t.printStackTrace();
} finally{
System.out.println(j);
}
}
}
Error occurred during initialization of VM
MaxMetaspaceSize is too small.
反编译字节码文件
/**
* 二进制字节码:类基本信息、常量池、类方法定义、虚拟机指令
*/
public class HelloWord {
public static void main(String[] args) {
System.out.println("Hello word!");
}
}
PS F:\software\IDEA\JavaProjects\JvmTest\target\classes\org\example\java\methodArea\changleiPool> javap -v HelloWord
警告: 二进制文件HelloWord包含org.example.java.methodArea.changleiPool.HelloWord
//----------------------类基本信息
Classfile /F:/software/IDEA/JavaProjects/JvmTest/target/classes/org/example/java/methodArea/changleiPool/HelloWord.cla
ss
Last modified 2022-11-7; size 612 bytes
MD5 checksum 8ac0f4a48d54619bddaec8c500042064
Compiled from "HelloWord.java"
public class org.example.java.methodArea.changleiPool.HelloWord
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
//----------------------常量池
Constant pool:
#1 = Methodref #6.#20 // java/lang/Object."":()V
#2 = Fieldref #21.#22 // java/lang/System.out:Ljava/io/PrintStream;
#3 = String #23 // Hello word!
#4 = Methodref #24.#25 // java/io/PrintStream.println:(Ljava/lang/String;)V
#5 = Class #26 // org/example/java/methodArea/changleiPool/HelloWord
#6 = Class #27 // java/lang/Object
#7 = Utf8 <init>
#8 = Utf8 ()V
#9 = Utf8 Code
#10 = Utf8 LineNumberTable
#11 = Utf8 LocalVariableTable
#12 = Utf8 this
#13 = Utf8 Lorg/example/java/methodArea/changleiPool/HelloWord;
#14 = Utf8 main
#15 = Utf8 ([Ljava/lang/String;)V
#16 = Utf8 args
#17 = Utf8 [Ljava/lang/String;
#18 = Utf8 SourceFile
#19 = Utf8 HelloWord.java
#20 = NameAndType #7:#8 // "":()V
#21 = Class #28 // java/lang/System
#22 = NameAndType #29:#30 // out:Ljava/io/PrintStream;
#23 = Utf8 Hello word!
#24 = Class #31 // java/io/PrintStream
#25 = NameAndType #32:#33 // println:(Ljava/lang/String;)V
#26 = Utf8 org/example/java/methodArea/changleiPool/HelloWord
#27 = Utf8 java/lang/Object
#28 = Utf8 java/lang/System
#29 = Utf8 out
#30 = Utf8 Ljava/io/PrintStream;
#31 = Utf8 java/io/PrintStream
#32 = Utf8 println
#33 = Utf8 (Ljava/lang/String;)V
//----------------------类方法定义
{
public org.example.java.methodArea.changleiPool.HelloWord();//构造方法
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."":()V
4: return
LineNumberTable:
line 3: 0
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this Lorg/example/java/methodArea/changleiPool/HelloWord;
public static void main(java.lang.String[]);//main方法
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String Hello word!
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
LineNumberTable:
line 5: 0
line 6: 8
LocalVariableTable:
Start Length Slot Name Signature
0 9 0 args [Ljava/lang/String;
}
SourceFile: "HelloWord.java"
public class InterviewQuestions {
public static void main(String[] args) {
//1.常量池中的信息,都会被加载到运行时常量池中
//2.这时的a b ab 都是运行时常量池中的符号,还没有变为 java 字符串对象
String s1="a";
String s2="b";
String s3="ab";
//3.在运行时常量池表中查询出 a符号、b符号、ab符号,然后在字符串常量池中查找对象,找不到再创建对象:StringTable[]{"a","b","ab"}
String s4=s1+s2;
//4.在局部变量表中加载到 "a"和"b" ,再创建对象:new String("ab")
String s5="a"+"b";
//5.在编译期间优化,结果已经在编译期确定为 ab符号,然后在字符串常量池中查找对象,找不到再创建对象:StringTable[]{"a","b","ab"}
System.out.println("s3==s4:"+(s3==s4));//false
System.out.println("s3==s5:"+(s3==s5));//true
System.out.println("s4==s5:"+(s4==s5));//false
}
}
将堆内存中的字符串对象添加到字符串常量池中
String s3 = "ab";
String s4 = new String("ab");
String s6 = s4.intern();
System.out.println(s3 == s6);//true:返回字符串常量池中的对象(即s3的引用)
String x2 = new String("c") + new String("d");
x2.intern();
String x1 = "cd";
System.out.println(x1 == x2);//jdk1.8:true。将堆内存中的对象添加到字符串常量池并返回
System.out.println(x1 == x2);//jdk1.6:false。重新创建对象添加到字符串常量池并返回新对象
jdk1.6:放在方法区(永久代)
jdk1.8
未添加前:1700+ 个
/**
* 演示 StringTable 垃圾回收
* -Xmx10m -XX:+PrintStringTableStatistics -XX:+PrintGCDetails -verbose:gc
*/
public static void main(String[] args) {
int i=0;
try {
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("添加到字符串常量池个数:"+i);
}
}
#垃圾回收信息:无
#打印信息:
添加到字符串常量池个数:0
#字符串常量池信息:未添加前存在1757个字符串
StringTable statistics:
Number of buckets : 60013 = 480104 bytes, avg 8.000
Number of entries : 1757 = 42168 bytes, avg 24.000
Number of literals : 1757 = 157720 bytes, avg 89.767
Total footprint : = 679992 bytes
添加10000个:应该有 11700+ 个,但只保留 2800+ 个
/**
* 演示 StringTable 垃圾回收
* -Xmx10m -XX:+PrintStringTableStatistics -XX:+PrintGCDetails -verbose:gc
*/
public static void main(String[] args) {
int i=0;
try {
for (int j = 0; j < 10000; j++) {
String.valueOf(j).intern();
i++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("添加到字符串常量池个数:"+i);
}
}
#垃圾回收信息:
[GC (Allocation Failure) [PSYoungGen: 2048K->488K(2560K)] 2048K->688K(9728K), 0.0010454 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
#打印信息:
添加到字符串常量池个数:10000
#字符串常量池信息:应该有 11700+ 个,但只保留 2800+ 个
StringTable statistics:
Number of buckets : 60013 = 480104 bytes, avg 8.000
Number of entries : 2867 = 68808 bytes, avg 24.000
Number of literals : 2867 = 211320 bytes, avg 73.708
Total footprint : = 760232 bytes
/**
* -XX:StringTableSize=200000 -XX:+PrintStringTableStatistics
*/
public static void main(String[] args) {
Long start=System.nanoTime();
for (int i = 0; i < 5000000; i++) {
String.valueOf(i).intern();
}
System.out.println("cost:"+(System.nanoTime()-start)/1000000+" ms");
}
不调整
#耗时
cost:4285 ms
#字符串常量池信息:桶数量为60013
StringTable statistics:
Number of buckets : 60013 = 480104 bytes, avg 8.000
Number of entries : 1422564 = 34141536 bytes, avg 24.000
Number of literals : 1422564 = 79723080 bytes, avg 56.042
Total footprint : = 114344720 bytes
调小
#耗时
cost:124604 ms
#字符串常量池信息:桶数量为1009
StringTable statistics:
Number of buckets : 1009 = 8072 bytes, avg 8.000
Number of entries : 249555 = 5989320 bytes, avg 24.000
Number of literals : 249555 = 14034576 bytes, avg 56.238
Total footprint : = 20031968 bytes
调大
#耗时
cost:2252 ms
#字符串常量池信息:桶数量为200000
StringTable statistics:
Number of buckets : 200000 = 1600000 bytes, avg 8.000
Number of entries : 1422584 = 34142016 bytes, avg 24.000
Number of literals : 1422584 = 79724200 bytes, avg 56.042
Total footprint : = 115466216 bytes
不入池
/**
* -XX:StringTableSize=200000
* 不入池
*/
public static void main(String[] args) throws IOException {
List<String> list=new ArrayList<>();
System.in.read();
for (int i = 0; i < 10; i++) {
Long start=System.nanoTime();
for (int j = 0; j < 500000; j++) {
list.add(String.valueOf(j));
}
System.out.println("cost:"+(System.nanoTime()-start)/1000000+" ms");
}
System.in.read();
}
入池
/**
* -XX:StringTableSize=200000
* 入池
*/
public static void main(String[] args) throws IOException {
List<String> list=new ArrayList<>();
System.in.read();
for (int i = 0; i < 10; i++) {
Long start=System.nanoTime();
for (int j = 0; j < 500000; j++) {
list.add(String.valueOf(j).intern());
}
System.out.println("cost:"+(System.nanoTime()-start)/1000000+" ms");
}
System.in.read();
}
Direct Memory
常见于 NIO 操作时,用于数据缓冲区
分配回收成本较高,但读写性能高
不受 JVM 内存回收管理
//内存溢出:java.lang.OutOfMemoryError: Direct buffer memory
public static void main(String[] args) {
List<ByteBuffer> list=new ArrayList<>();
int i=0;
try {
while(true){
ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 100);
list.add(buffer);
i++;
}
} finally {
System.out.println(i); //17
}
}
//分配,返回地址
Long base=unsafe.allocateMemory(1024*1024*1024);
unsafe.setMemory(base, 1024*1024*1024, (byte) 0);
注意与建议:不依赖gc的情况下,可以使用 unsafe 手动管理直接内存
ByteBuffer 的实现类内部,使用了 **Cleaner (虚引用)**来监测 ByteBuffer 对象,一旦 ByteBuffer 对象被垃圾回收,那么就会由 ReferenceHandler 线程通过 Cleaner 的 clean 方法调 用 freeMemory 来释放直接内存
//释放内存
unsafe.freeMemory(base);
随着gc的调用而回收?
释放原理
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
//调用 直接缓存 的构造方法
DirectByteBuffer(int cap) {
//...
try {
//1.分配内存
base = unsafe.allocateMemory(size);
} catch (OutOfMemoryError x) {
Bits.unreserveMemory(size, cap);
throw x;
}
//2.设置内存
unsafe.setMemory(base, size, (byte) 0);
if (pa && (base % ps != 0)) {
address = base + ps - (base & (ps - 1));
} else {
address = base;
}
//3.释放内存:当Cleaner关联的 this对象 被回收时,触发 clean()
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
att = null;
}
//3.1 触发回调对象的run方法
public void clean() {
if (remove(this)) {
try {
//3.1 调用
this.thunk.run();
} catch (final Throwable var2) {}
}
}
//3.2 Cleaner中的 new Deallocator 回调任务
public void run() {
//...
//释放直接内存
unsafe.freeMemory(address);
address = 0;
Bits.unreserveMemory(size, capacity);
}