Sunday, 29 July 2012

Java Virtual Machine - Lifetime

An instance of JVM has only one purpose in its life - to run a java application.
When a java application starts, an instance of JVM is born. When the application completes, the instance dies.

About main() method
A JVM instance starts running its application by invoking the main() method of some initial class. The main() method must be public, static, return void, and accept one parameter: a String array. Any class with such a main() method can be used as the starting point for a Java application. 
For example, consider an application that prints out its command line arguments:
class PrintArgs{ 

    public static void main(String[] args) {

        int len = args.length;
        for (int i = 0; i < len; ++i) {
            System.out.print(args[i] + " ");

There must be a way in which we give JVM the name of the initial class that has the main() method that will start the entire application. One example is the java program from Sun's SDK. To run PrintArgs application using Sun's java, we would type the below command:
     java PrintArgs welcome, here.

The first word in the command, "java," indicates that the JVM from Sun’s JDK should be run by the OS. The second word, " PrintArgs," is the name of the initial class. PrintArgs must have a public static method named main() that returns void and takes a String array as its only parameter. The subsequent words, " welcome, here.," are the command line arguments for the application.

The main() method of an application’s initial class serves as the starting point for that application’s initial thread. The initial thread can then fire off other threads.
Inside the JVM, threads come in two flavors: daemon and non-daemon.

Daemon thread: it is ordinarily a thread used by the VM itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads.

Non-daemon thread: 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.

In the  PrintArgs application above, the main() method doesn’t invoke any other threads. After it prints out the command line arguments, main() returns. This terminates the application’s only non-daemon thread, which causes the virtual machine instance to exit.

No comments:

Post a Comment