The more JVM memory, the less threads can be created, the more likely java. lang. OutOfMemoryError: unable to create new native thread .,
I. Understanding:
First, we will understand this problem through the following test program:
Running Environment (it is worth noting that different environments have different results): 32-bit Windows XP, Sun JDK 1.6.0 _ 18, eclipse 3.4,
Test procedure:
Java code
If no JVM parameter is specified, the output is directly run in eclipse. You can see this friend:
I = 5602.
Exception in thread "main" java. lang. OutOfMemoryError: unable to create new native thread
At java. lang. Thread. start0 (Native Method)
At java. lang. Thread. start (threads. java: 597)
At TestNativeOutOfMemoryError. main (TestNativeOutOfMemoryError. java: 20)
Ii. analyze the problem:
The root cause of this exception is that we have created too many threads, and the number of threads that can be created is limited, resulting in exceptions. The formula for calculating the number of threads that can be created is as follows:
(MaxProcessMemory-JVMMemory-ReservedOsMemory)/(ThreadStackSize) = Number of threads
MaxProcessMemory refers to the maximum memory of a process.
JVMMemory JVM memory
Operating system memory retained by ReservedOsMemory
ThreadStackSize the size of the thread Stack
In java, when you create a Thread, the virtual opportunity creates a Thread object in the JVM memory and creates an operating system Thread at the same time. The memory of this system Thread is not JVMMemory, but the remaining memory in the system (MaxProcessMemory-JVMMemory-ReservedOsMemory ).
The formula is described based on the above example:
MaxProcessMemory is 2 GB in 32-bit windows
By default, JVMMemory eclipse starts 64 MB of program memory.
ReservedOsMemory is usually around MB
ThreadStackSize 32-bit JDK 1.6 default stacksize about K
The formula is as follows:
(2*1024*1024-64*1024-130*1024)/325 = 5841
The formula calculates 5841, which is basically the same as the practice 5602 (there is a deviation because ReservedOsMemory cannot be accurate)
According to the formula, the more JVM memory you provide, the less threads you can create, and the more likely java. lang. OutOfMemoryError: unable to create new native thread.