Thursday, April 12, 2007

How is your Java program executed inside JVM?

When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.

This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.

If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.

There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.

Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.

2 comments :

Madhusudan on November 28, 2010 at 11:44 PM said...

Great explanation!!! However, I would like to know how the other java applications works in JVM, if the main() method is not there. Such as Servlets and JSPs? Internally, any Browser or a web container or a System which supports a Java application, does need to have a JVM. So, how does it work in any web enabled environment?

Abhijith said...

@Madhusudan,

All web applications developed using Servlets or JSPs (etc.) will have main methods which are internally implemented by web application servers. The main method need not be implemented by the developers while writing JSP or Servlets (etc.). If you want to understand more on this, then check some web servers like Tomcat or application servers like JBoss.

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker