JAVA

Memory leak - Thread dump 활용

junseokoh 2022. 7. 10. 02:22

서버 접속 장애 발생

터널링해서 top 명령을 실행했을 때 java 프로세스가 100% 이상 튀는 문제 발생

서버 로그를 통해서는 확인이 되지 않는 상황

이 때, 쓰레드 덤프, 힙 덤프를 뜨면 확인할 수 있을 것으로 판단함

우선 java 프로세스를 확인

$ ps -efc | grep java

그리고 gc를 확인할 수 있는 명령어 몇 개 실행

$ jstat -gc <pid>
$ jstat -gc 10985

$ jstat -gcutil <pid>
$ jstat -gcutil 11479

$ jstat -gcutil -h5 <pid> 1000 10
$ jstat -gcutil -h5 11479 1000 10

위 명령으로는 정확한 확인이 어려워서 ThreadDump 생성

$ jstack <pid> > threadDump.txt
$ jstack 10895 > threadDump.txt

headDump도 생성

$ jstat -dump:format=b,file=heapdump.hprof <pid>
$ jstat -dump:format=b,file=heapdump.hprof 10895

$ jmap -dump:live,file=heapdump.hprof <pid>
$ jmap -dump:live,file=heapdump.hprof 10895

ThreadDump에 대한 확인을 할 수 있는 Online 사이트 존재

https://fastthread.io/ft-index.jsp

 

fastthread.io

Thread Dump Analysis REST API In this modern world, thread dumps are still analyzed in a tedious & manual mode. i.e., Operations engineer captures thread dumps from the production servers; then he transmits those files to developers. Developers use thread

fastthread.io

아주 상세한 리포트를 확인할 수 있다.

하지만, ThreadDump 로는 명확한 문제확인을 하지 못했다.

그래서 HeapDump도 확인해 봤다.

HeapDump는 IBM의 HeapAnalyzer 와 Eclipse의 Memory Analyzer(MAT) 를 사용 했다.

- IBM 다운로드 사이트 : https://www.ibm.com/support/pages/ibm-heapanalyzer

- MAT 다운로드 사이트 : https://www.eclipse.org/mat/

IBM HeapAnalyzer 실행 시 heap 메모리가 heapDump size보다 작으면 heapDump 파일을 분석하지 못한다.

나는 8g까지 줬을 때 heapDump 파일을 분석할 수 있었다.

$ java -Xmx8g -jar ha*.jar

IBM Leak Suspect 확인

Leak Suspect

Mat의 경우도 heap memory를 늘려줘야 한다.

Mac의 경우 응용프로그램에서 MAT 을 우클릭하면 패키지 내용 보기를 선택할 수 있다. 

패키지 내용보기를 선택하면 MAT 프로그램 파일들을 볼 수 있다.

여기서 경로는 Contents > Eclipse > MemoryAnalyzer.ini

여기서 -Xmx6g 옵션을 설정했다.

MAT Leak Suspects 확인

확인 결과, while 문이 무한루프로 돌면서 List에 계속해서 add하고 있었다. 

몇천만개가 넘어가다 보니, Memory leak 발생으로 접속장애가 발생했었다.

내가 짠 코드는 아니지만 while 문의 경우, 언제나 조건을 빠져나올 수 있는지 체크하는 습관을 가지는게 좋을 것 같다.

요약하자면,

  • 프로세스 확인 방법
  • ThreadDump 뜨는 방법
  • HeapDump 뜨는 방법
  • ThreadDump 온라인 분석
  • HeapDump 로컬 분석 툴 (IBM, Eclipse MAT)
  • IBM, Eclipse Heap 메모리 설정 실행 이슈

 

기회가 된다면, dump 파일들의 상세 설명과, 분석 방법에 다루면 좋을 것 같다.