grep

Engineering

우리의 Thread는 왜 이렇게 부자가 되었을까?

NHN

2021년 7월 12일

원문에서 보기 ↗

안녕하세요. NHN Cloud 서비스에서 공통적으로 사용되는 Framework(결제, 인증, 권한 등)를 개발하고 있는 프레임워크개발팀 박시우입니다. 최근 저희 팀에서 OOM 이슈 관련하여, 분석해 본 결과 병렬 처리 진행을 위해 ForkJoinPool을 사용하게 되면서 겪은 이슈에 대해 공유드리고자 합니다. 발생 시점부터, 무엇이 문제였는지 상세히 작성하였고 기본적인 내용도 포함되어 있으므로 한 번쯤 시간 나실 때 담당하시는 서비스도 확인해보시면 좋을 것 같아 글을 쓰게 되었습니다.

1. 문제 발생

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached

2. 분석

다른 게 부자여야 하는데 Thread가 왜 이렇게 부자가 되었을까요??

3. 이슈 확인

4. ForkJoinPool 분석

ForkJoinPool?

5. 의심

잠깐.. 이 코드는 변경된 적이 없는데?? 8에서 11로 올라온 지가 며칠 되지 않았고, 8에서는 ForkJoinPool이 문제가 없었나??

5.1 여기서 문득 머릿속을 스쳤던 생각

5.2 의심이 사실이 되어버리는 순간...

  1. 명시적으로 Shutdown() 해주는 방법이 있고
  2. 암시적으로 Thread Pool 이 해제되는 Case가 어떤 경우가 있는가?를 파헤쳐 보기 시작합니다.

Java 8에서의 테스트 (ForkJoinPool의 동작 방식을 알기 위해 Local에서 테스트 코드 작성)

4.png

Java 11에서의 테스트

6.png

6. 재 의심

7. 추적

8. 증명

결국 11의 ForkJoinPool 이 정상적으로 반납되지 않는 현상은 위와 같은 이슈였고.. 아 안되나 보다 라고 마음을 다잡고 있는 와중에 구글링을 하다 보니 같은 실험을 하는 개발자가 있었고.. https://stackoverflow.com/questions/54084915/forkjoinpool-performance-java-8-vs-11

In practice, the observed behavior stems from an undocumented idle timeout of two seconds. Note that according to the comment, the consequence of an elapsed timeout is an attempt to shrink the number of workers which is different to just terminating. So if n thread experience the timeout, not all n threads terminate but the number of threads gets reduced by one and the remaining threads may wait again. Further, the phrase “initial timeout value” already hints at it, the actual timeout gets incremented each time it happens. So it takes n * (n  + 1) seconds for n idle worker thread to terminate due to this (undocumented) timeout.

9. 결론

10. 마치며

최종 결론

Java 8과 11의 Thread Executor 동작 메커니즘이 다르다. Spring boot를 쓰는 이상 Thread Pool을 일회용으로 쓰지 않기 때문에 문제는 없지만 만약 일회성으로 쓴다면 shutdown을 신경 써야 한다.

●섬네일 이미지 출처: https://javatechnocampus.wordpress.com/2015/10/03/544/