Maximum number of Thread

Calculation of maximum number of thread with different stack size

Every thread is allocated a stack which is used for thread's operation. In this way JVM can support a fixed number of threads. Increasing number of thread beyond that limit would result in crashing of JVM.

Default stack size depends on VM(virtual machine). During execution of java program, size of stack can be changed by using -Xss option.

Program for calculating maximum number of thread

Following program will show maximum number of thread supported by JVM with given stack size

class mythread implementing Runnable interface. run() method is defined for infinite execution. So whenever a thread is created using mythread class that thread will run forever.

Now what we are interested in is maximum number of thread which can be supported by JVM. So we will try to create specified number of thread. If program run without any exception it means that number of thread supported by jvm, otherwise that number of thread can't be supported.



// Thread Stack Analysis
// www.jgyan.com
class st
 {
  public static void main(String arg[])
  {
   int i=0;
   if(arg.length==0)
	System.out.println(" Usage: Provide number of thread \n  java st 500");
   else
	{
	try
	{
	 int a=Integer.parseInt(arg[0]);
	 long t1=System.nanoTime();
	 Thread th;
	 for( i=0;i<a;i++)
	  {
	   th=new Thread(new mythread());
       th.start();				 
	  }
	 long t2=System.nanoTime();
	 System.out.println("Time: "+(t2-t1)/1000000+"ms for creating "+a +" threads");
	}
	catch(OutOfMemoryError oe)
	 {
	  System.out.println("\nError while creating "+i+" thread \n Not enough Memory....");
	  System.exit(0);
     }
	catch(NumberFormatException e)
    {
	 System.out.println("\n Please provide integer number as argument");
	}		 
  }
 }
}
 
// Class for creating thread
class mythread implements Runnable
 {
  public void run()
   {
    // infinity loop : Thread will run forever 
	for(;;)
	{
	try{
	  Thread.sleep(1000);
	   } 
	catch(InterruptedException e){
	  System.out.println("Thread interrupted");
	  }
	 }
   }
 }   
  



Execution:

For execution of above program we need to pass one command line argument specifying number of thread.


C:\Users\jgyan\Desktop>java -Xss512 st 1000
Time: 78ms for creating 1000 threads

For terminating program press ctrl+c because all of our thread will be running forever(infinity loop).
Now we will try to create more thread to check maximum number of thread supported by our jvm.


C:\Users\jgyan\Desktop>java -Xss512 st 3000

Error while creating 1857 thread 
 Not enough Memory....