Martin Tarjányi
Martin Tarjányi

Reputation: 9967

Creating threads in infiinite loop

My understanding is that every new thread allocates 1MB of memory for its stack.

I would expect that if I created threads in an infinite loop, then sooner rather than later I would run out of memory and when I would check the memory consumption of the java process I would see for example 4GB of memory consumed by 4000 threads.

Instead my little dummy application creates more thousands of threads but the memory consumption is way below the expected (~250MB based on windows task manager for 4000 threads and used system memory is also much lower than expected). Could somebody explain why that is happening?

public static void main(String[] args) {
    int i = 1;
    while (true) {
        new Thread(() -> waitForMillis(6000000)).start();
        System.out.println(i++);
        waitForMillis(100);
    }
}

private static void waitForMillis(int millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Views: 72

Answers (1)

davidbak
davidbak

Reputation: 6019

You're using up 1Mb of virtual address space for each stack, but only a minimal amount of actual memory is allocated for each stack until it is actually used. 64Kb, usually, on Windows. Read up on operating system process memory allocation - specifically the difference between allocated (aka reserved) virtual address space on the one hand and committed memory on the other.

Here's one description that may help: Reserving and Committing Memory (MSDN)

Upvotes: 2

Related Questions