spring boot 模擬飈高代碼
@Service
public class TestWhile
{
/* 操作內存對象 */
ConcurrentHashMap map = new ConcurrentHashMap();
private void whileTrue(String threadName) {
// 不設置退出條件,死循環
while (true) {
// 在死循環中不斷的對map執行put操作,導致內存gc
for (int i = 0; i <= 100000; i++) {
map.put(Thread.currentThread().getName() + i, i);
} // end for
}// end while
}
@PostConstruct
public void testWhile() {
// 循環size,創建多線程,並發執行死循環
for (int i = 0; i < 20; i++) {
int finalI = i;
// 新建並啟動線程,調用whileTrue方法
new Thread(() -> {
whileTrue("李文-" + finalI);
}).start();
}
}
}
public class TestWhile
{
/* 操作內存對象 */
ConcurrentHashMap map = new ConcurrentHashMap();
private void whileTrue(String threadName) {
// 不設置退出條件,死循環
while (true) {
// 在死循環中不斷的對map執行put操作,導致內存gc
for (int i = 0; i <= 100000; i++) {
map.put(Thread.currentThread().getName() + i, i);
} // end for
}// end while
}
@PostConstruct
public void testWhile() {
// 循環size,創建多線程,並發執行死循環
for (int i = 0; i < 20; i++) {
int finalI = i;
// 新建並啟動線程,調用whileTrue方法
new Thread(() -> {
whileTrue("李文-" + finalI);
}).start();
}
}
}
top
使用 淘寶開源 show-busy-java-threads 快速排查
- 介紹:
- 作者 :淘寶 李鼎(哲良) oldratlee
- 用於快速排查Java的CPU性能問題(top us值過高),自動查出運行的Java進程中消耗CPU多的線程,並打印出其線程棧,從而確定導致性能問題的方法調用。
- Git地址:https://github.com/oldratlee/useful-scripts
執行: curl -sLk 'https://raw.github.com/oldratlee/useful-scripts/release-2.x/bin/show-busy-java-threads' | bash -s -- -a 2.log
輸出到 2.log 文件。
結果:GC引起的CPU 飈高, 【5】 引起GC的線程與執行代碼方法。 可以定位到 whileTrue 方法有問題。
使用 淘寶開源 Arthas 排查問題
- 介紹: Arthas 是Alibaba開源的Java診斷工具 ,業界最強。
- GIT地址 : https://github.com/alibaba/arthas/blob/master/README_CN.md
- 不光是CPU線程問題排查,幾乎可以包括所有問題的排查,在線反編譯,動態熱更新運行中的代碼,在線請求鏈路跟蹤等等功能。
curl -O https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar
選擇需要排查的那個進程
1 + Enter
執行 dashboard 命令
初步可以判斷為GC引發的CPU飈高
執行 thread -n 3 -i 5000 查看CPU使用率Top N線程的棧
結果: GC引起的CPU 飈高, 可以定位到線程運行鏈接方法 whileTrue 有問題。
推薦在服務出現問題, 執行以下 c curl -sLk 'https://raw.github.com/oldratlee/useful-scripts/release-2.x/bin/show-busy-java-threads' | bash -s -- -a 2.log 然后在重啟,這樣重啟后也會有寫問題記錄