ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JVM은 몇 개의 Thread를 생성할수 있을까?
    Java 2022. 8. 22. 16:13

    문득 JVM은 몇 개의 thread를 생성할수 있을까? 라는 생각이 들어 정리합니다.

     

    일단, 정답은 "몇 개를 생성하는지 정확히 알수 없다" 입니다.

    해당 포스트에는 JVM이 생성할수 있는 최대 Threads 영향을 미치는 Factor를 정리합니다.


    Stack Memory

    Thread 구성 중 가장 중요한 요소 중 하나는 Stack 입니다.

    Thread가 생성되면 동시에 Thread Stack도 생성되고 Frame에 저장합니다.

    (Stack size를 지정하지 않으면 JVM이 Default size로 stack을 생성합니다.)

    생성하는 최대 스택 크기와 Thread 수는 사용 가능한 시스템 메모리와 직접적인 관계가 있습니다.

    따라서, 메모리 용량을 늘리면 시스템에서 생성할수 있는 Thread 수도 늘어납니다.

    Thread 수 = (system memory - jvm memory - reserved o/s memory) / thread stack size

    System (Linux 기준)

    Linux Kernal은 Thread는 프로세스로 취급합니다.

    (프로세스 수를 제한하는 것은 간접적으로 Thread 수를 제한하는 것과 동일합니다.)

    따라서, kernel.pid_max는 threads-max보다 커야합니다.

    threads-max

    Kernal이 최대 n개의 Thread를 실행할 수 있음을 나타냅니다.

    sysctl kernel.threads-max
    또는
    cat /proc/sys/kernel/threads-max

    pid_max

    Kernal이 동시에 최대 n개의 프로세스를 실행할 수 있음을 나타냅니다.

    sysctl kernel.pid_max
    또는
    cat /proc/sys/kernel/pid_max

    max_map_count

    프로세스가 소유할 수 있는 가상 메모리 영역의 최대 수를 나타냅니다.

    sysctl vm.max_map_count
    또는
    cat /proc/sys/vm/max_map_count

    Heap 메모리

    Heap은 실행할 수 있는 thread 수에 영향을 주진 않지만 갑분 heap memory가 왜? 라는 의문이 있을 수 있겠지만.

    heap memory 역시 system memory를 사용하고 heap size가 늘어나면 stack에 사용할수 있는 메모리가 제한되니 생성할수 있는 최대 thread 수에 영향을 줄수 있습니다.

     

     

    현재 생성 할 수 있는 Thread 수를 확인 하는 코드

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class ThreadTest {
    	public static AtomicInteger count = new AtomicInteger();
    
    	public static void main(String[] args) {
    		while (true) {
    			getThread().start();
    		}
    	}
    
    	private static Thread getThread() {
    		Thread thread = new Thread(() -> {
    			try {
    				count.getAndIncrement();
    				Thread.sleep(Integer.MAX_VALUE);
    			} catch (InterruptedException e) {
    				throw new RuntimeException(e);
    			}
    		});
    		return thread;
    	}
    
    }

     

     

    이상.

Copyright 2022. 0woong-developer all rights reserved.