背景
IntelliJ IDEA 与以下分析工具集成:
-
Async Profiler:适用于 Linux 和 macOS 的 CPU 和内存分析工具。 -
Java Flight Recorder:Oracle 提供的 CPU 工具,可在 Linux、macOS 和 Windows 上使用。
使用简介
public class Demo {
public static void main(String[] args) {
for (int i = 0; i < 10000000; i++) {
System.out.println(produceString());
}
}
private static String produceString() {
return "Hello World";
}
}
选择 【Run 'xxx' with 'Java Flight Recorder'】

Run 'xxx' with 'Java Flight Recorder'
会出现如下错误:
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Error: To use 'FlightRecorder', first unlock using -XX:+UnlockCommercialFeatures.
在 VM options 中添加 -XX:+UnlockCommercialFeatures 参数。

在【Profiler】窗口点击【Stop Profiling and Show Results】

然后就可以看到结果。
Profiler 展示图表
1. Flame Graph(火焰图)

Flame Graph
2. Call Tree(调用树)

Call Tree
3. Method List(方法列表)

Method List
F4 调转到源码:

image.png
实战演练
public class Demo {
@SneakyThrows
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
System.out.println(produceString());
}
System.out.println("准备进入需要测试的方法");
testMethod();
System.out.println("已经从测试的方法返回");
Thread.sleep(10 * 1000);
}
private static String produceString() {
return "Hello World";
}
private static void testMethod() {
int count = 0;
for (int i = 0; i < 30; ++ i) {
timeConsuming();
}
System.out.println(count);
}
@SneakyThrows
private static void timeConsuming(){
for (int i = 0; i < 20000; ++ i) {
byte[] temp = new byte[10000];
new Random().nextBytes(temp);
}
}
}
假设 testMethod() 方法执行耗时太长,我们需要排查时间花费在哪里。
排查步骤如下所示:
-
1)在需要排查的方法前后打上断点(这个方法,可能是根据日志中的执行时间识别出来的),如下图所示。
image.png 2)以 debug 模式启动项目。(需要在 VM options 中添加
-XX:+UnlockCommercialFeatures参数。)-
3)在第一个断点(需要排查的方法前一行语句)暂停时,在 Profiler 创建选择第(1)步启动 JVM 进程(
Process Name一般会展示为 main 函数所在的类)进行Attach Profiler to Process...的操作。如下图所示
- 4)继续运行之前的项目,在第二个断点暂停时,在【Profiler】窗口点击【Stop Profiling and Show Results】,然后继续运行之前的项目。

通过【Flame Graph】可以看出,java.util.Random#nextBytes 调用栈的采样率为 99.43%。表示 CPU 大部分时间都在执行 java.util.Random#nextBytes 函数。和预期一致!

