With Java for so long, can you say the Java boot process? Don't blow it, come see

Source: Internet
Author: User
Tags goto sprintf

First of all to go to openjdk the source code. I'm down here to openjdk-7-fcs-src-b147-27_jun_2011.

</pre>java.exe the start of this program main function in <br style= "padding:0px; margin:0px; Outline:none; List-style:none; border:0px None "/><strong>java.c (hotspot\src\share\tools\launcher) </strong><br style=" padding : 0px; margin:0px; Outline:none; List-style:none; border:0px None "/>main function is implemented as follows: <p></p><p style=" PADDING-TOP:1EM; Padding-bottom:1em; margin-top:0px; margin-bottom:0px; Outline:none; List-style:none; border:0px none; Color:rgb (51,51,51); font-family: ' Droid Sans ', Arial,verdana,sans-serif; font-size:16px; line-height:24px; Orphans:2;    Widows:2 "></p><pre name=" code "class=" java "> Char *jarfile = 0;    char *classname = 0;    char *s = 0;    char *main_class = NULL;    int ret;    Invocationfunctions IFN;    Jlong start, end;    Char Jrepath[maxpathlen], Jvmpath[maxpathlen];    char * * original_argv = argv;        if (getenv ("_java_launcher_debug")! = 0) {_launcher_debug = Jni_true;    printf ("----_java_launcher_debug----\ n"); } #ifndeF GAMMA/* * Make sure that the version is 1.4, 1.5, 1.6 * Do sure the specified version of the JRE is running. * * There is three things to note about the Selectversion () routine: * 1) If The version running isn ' t correct,     This routine doesn ' t * return (either the correct version have been exec ' d or an error * was issued).     * 2) ARGC and Argv in this scope is *not* altered by this routine.     * It is the responsibility of subsequent code to ignore the * arguments handled by this routine.  * 3) as a side-effect, the variable "Main_class" is guaranteed to * BES set (if it should ever be set).  This isn ' t exactly the * poster-structured programming, but it's a small * price-pay-for-not     Processing a jar file operand twice.  * (Note:this side effect has been disabled.     See comment on * bugid 5030265 below.) */Selectversion (argc, argv, &main_class); #endif/* ifndef GAMMA *//* Take the parametersCome out */{int i;      ORIGINAL_ARGV = (char**) jli_memalloc (sizeof (char*) * (argc+1));    for (i = 0; i < argc+1; i++) original_argv[i] = Argv[i];                               /** * Create an execution environment, such as to see if the JRE is installed, read the path to the JRE, Jvm.cfg */createexecutionenvironment (&AMP;ARGC, &AMP;ARGV,                               Jrepath, sizeof (Jrepath), Jvmpath, sizeof (Jvmpath),    ORIGINAL_ARGV);    printf ("Using Java Runtime at:%s\n", Jrepath); Ifn.    CREATEJAVAVM = 0; Ifn.    Getdefaultjavavminitargs = 0;    A timer, such as if (_launcher_debug) start = Counterget (); Loaded into the JVM loaded DLL, here will call JNI_CREATEJAVAVM, the JVM thread run up if (!    LOADJAVAVM (Jvmpath, &AMP;IFN)) {exit (6);      }//timer, how long does it take to open the JVM thread if (_launcher_debug) {end = Counterget ();    printf ("%ld micro Seconds to loadjavavm\n", (long) (Jint) Counter2micros (End-start)); } #ifdef Java_args/* Javac, jar and friends. */progname = "java"; #else/* java, OLdjava, JAVAW and friends * * #ifdef progname progname = progname; #else progname = *ARGV;    if ((s = STRRCHR (Progname, file_separator))! = 0) {Progname = s + 1;    } #endif/* progname */#endif/* Java_args */++argv;    --ARGC; #ifdef Java_args/* Handles the parameters of the command line */Translateapplicationargs (&AMP;ARGC, &AMP;ARGV); if (!    Addapplicationoptions ()) {exit (1);    } #endif/* Set the default CLASSPATH */if ((s = getenv ("CLASSPATH") = = 0) {s = ".";  } #ifndef Java_args Setclasspath (s); #endif/* * Parse command-line arguments, such as-jar-cp-help-h-version *-verbose:gc-xdebug -xverify-xrunhprof and so on are handled here */if (!    Parsearguments (&AMP;ARGC, &AMP;ARGV, &jarfile, &classname, &ret, Jvmpath)) {exit (ret);    }/* Special deal with-jar's classpath */if (jarfile! = 0) {Setclasspath (jarfile);    }/* Set The-dsun.java.command pseudo property */Setjavacommandlineprop (classname, Jarfile, argc, argv); /* Set The-dsun.java.launcher Pseudo ProperTy */Setjavalauncherprop (); /* Set the-dsun.java.launcher.* Platform Properties */Setjavalauncherplatformprops (); #ifndef GAMMA/* Show the SPL Ash screen if needed */ShowSplashScreen (); #endif/* * Do with all command line processing and potential Re-ex     ECS so * clean up the environment.    */(void) unsetenv (env_entry), #ifndef GAMMA (void) unsetenv (splash_file_env_entry); (void)    Unsetenv (Splash_jar_env_entry);    Jli_memfree (Splash_jar_entry); Jli_memfree (splash_file_entry); #endif/* * Thread stack size setting, no setting is default 0 */if (threadstacksize = = 0) {struct JD      K1_1initargs args1_1;      memset ((void*) &args1_1, 0, sizeof (args1_1));      Args1_1.version = jni_version_1_1; Ifn.  Getdefaultjavavminitargs (&args1_1);      /* Ignore return value */if (Args1_1.javastacksize > 0) {threadstacksize = args1_1.javastacksize;      }} {/* Java parameters give this parameter to the Javamain method, execute the Javamain method */struct Javamainargs args; ARGS.ARGC = argc      ARGS.ARGV = argv;      Args.jarfile = Jarfile;      Args.classname = classname;      ARGS.IFN = IFN;    Execute Javamain, which is the main function of Java return Continueinnewthread (Javamain, Threadstacksize, (void*) &args); }


The Continueinnewthread method creates a thread to execute the Javamain, so the Javamain is executed later.

The Javamain is this:

   The first is to get the command line parameters to execute the classname jar things like struct javamainargs *args = (struct Javamainargs *) _args;    int argc = args->argc;    Char **argv = args->argv;    Char *jarfile = args->jarfile;    Char *classname = args->classname;    Invocationfunctions IFN = args->ifn;    JAVAVM *VM = 0;    JNIEnv *env = 0;    Jstring Mainclassname;    Jclass MainClass;    Jmethodid Mainid;    Jobjectarray Mainargs;    int ret = 0;    Jlong start, end; /* * Error message to print or display;     By default the message would * is displayed in a window.  */char * message = "Fatal exception occurred.    Program would exit. ";    Jboolean messagedest = Jni_false;    /* Initialize the virtual machine *//Timer comes again if (_launcher_debug) start = Counterget (); Initialize JVM virtual machine here mainly to call the JNI_CREATEJAVAVM--&GT;THREADS::CREATE_VM//Here do a lot of things, THREADS::CREATE_VM later analysis.    Just know to get the JVM up here. if (! INITIALIZEJVM (&AMP;VM, &env, &AMP;IFN)) {reporterrormessage ("Could not create thE Java virtual machine. ", jni_true);    Exit (1);        } if (PrintVersion | | showversion) {printjavaversion (env);            if ((*env)->exceptionoccurred (env)) {reportexceptiondescription (env);        Goto leave;            } if (printversion) {ret = 0;            message = NULL;        Goto leave;        } if (showversion) {fprintf (stderr, "\ n");        }}//MainClass and jar always specify a bar, otherwise Java cannot run */if (Jarfile = = 0 && classname = = 0) {printusage ();        message = NULL;    Goto leave;  } #ifndef GAMMA Freeknownvms ();        /* After last possible printusage () */#endif//origin of a timer if (_launcher_debug) {end = Counterget ();    printf ("%ld micro Seconds to initializejvm\n", (long) (Jint) Counter2micros (End-start));        }/* Got the parameters for the application print a look at */if (_launcher_debug) {int i = 0; printf ("Main-class is '%s ' \ n", classname? classname : "");        printf ("Apps ' argc is%d\n", argc);        for (; i < argc; i++) {printf ("argv[%2d] = '%s ' \ n", I, argv[i]);    }} ret = 1;        /* * Get mainclass * * * if (jarfile! = 0) {mainclassname = Getmainclassname (env, jarfile);            if ((*env)->exceptionoccurred (env)) {reportexceptiondescription (env);        Goto leave;                                } if (mainclassname = = NULL) {const char * format = "Failed to load Main-class manifest"          "Attribute from\n%s";          Message = (char*) jli_memalloc ((strlen (format) + strlen (jarfile)) * sizeof (char));          sprintf (message, format, jarfile);          Messagedest = Jni_true;        Goto leave;        } classname = (char *) (*ENV)->getstringutfchars (env, mainclassname, 0);            if (classname = = NULL) {reportexceptiondescription (env);        Goto leave; }//Load class into MaincLass, it is the jclass structure MainClass = loadclass (env, classname); if (MainClass = = NULL) {/* Exception occured */const char * format = "Could not find the main class:%s. progr            Am would exit. ";            Reportexceptiondescription (env); Message = (char *) Jli_memalloc ((strlen (format) + strlen (classname)) * sizeof (CH            AR));            Messagedest = Jni_true;            sprintf (message, format, classname);        Goto leave;    } (*ENV)->releasestringutfchars (env, mainclassname, classname);      } else {//In case the jar is processed here, there is no case of specifying a jar Mainclassname = newplatformstring (env, classname);        if (Mainclassname = = NULL) {const char * format = "Failed to load Main Class:%s";        Message = (char *) Jli_memalloc ((strlen (format) + strlen (classname)) * sizeof (char));        sprintf (message, format, classname);        Messagedest = Jni_true;    Goto leave;  } classname = (char *) (*ENV)->getstringutfchars (env, mainclassname, 0);        if (classname = = NULL) {reportexceptiondescription (env);      Goto leave;      }//above processing UTF8, I have not seen, should not be the core regardless of, here load mainClass mainClass = loadclass (env, classname);  if (MainClass = = NULL) {/* Exception occured */const char * format = "Could not find the main class:%s.        Program would exit. ";        Reportexceptiondescription (env); Message = (char *) Jli_memalloc ((strlen (format) + strlen (classname)) * sizeof (char)        );        Messagedest = Jni_true;        sprintf (message, format, classname);      Goto leave;    } (*ENV)->releasestringutfchars (env, mainclassname, classname);                                       }/* Find MainClass Main method Of course this main must be by the string[] parameter of */Mainid = (*env)->getstaticmethodid (env, MainClass, "main",    "([ljava/lang/string;) V"); If you can't find it, you hang up. if (Mainid = = NULL) {if (*env)Exceptionoccurred (env)) {reportexceptiondescription (env);          } else {message = "No Main method found in specified class.";        Messagedest = Jni_true;    } goto leave;        } {/* Main function must be public */Jint mods;        Jmethodid mid;                                                Here is the Java.lang.reflect.Method jobject obj = (*env)->toreflectedmethod (env, MainClass,        Mainid, jni_true);            if (obj = = NULL) {/* exception occurred */Reportexceptiondescription (env);        Goto leave; }//A reflection calls the Java.lang.reflect.Method.getModifiers//find modifier to see if it is public mid = (*env)->ge Tmethodid (env, (*ENV)->getobjectclass (env, obj), "Getmodifier        S "," () I ");            if ((*env)->exceptionoccurred (env)) {reportexceptiondescription (env);        Goto leave; }//Public is 1, this look in Java code can be foundAll definitions of mods = (*env)->callintmethod (env, obj, mid); if (mods & 1) = = 0) {/* if (!            Modifier.ispublic (mods)) ... */message = "Main method not public.";            Messagedest = Jni_true;        Goto leave;    }}/* Put all the parameters of the Java program */Mainargs = Newplatformstringarray (env, argv, ARGC);        if (Mainargs = = NULL) {reportexceptiondescription (env);    Goto leave;    }/* Call Java's Main method */(*ENV)->callstaticvoidmethod (env, MainClass, Mainid, Mainargs); /* * * The exception return value is 0 */ret = (*env)->exceptionoccurred (env) = = NULL?    0:1;  /* * Detach the main thread so, it appears to has ended when * the application ' s main method exits.  This would invoke the * uncaught exception handler Machinery if main threw an * exception.     An uncaught exception handler cannot change the * launcher ' s return code except by calling System.exit.      */if ((*VM)->detachcurrentthread (VM)! = 0) {  Message = "Could not detach main thread.";        Messagedest = Jni_true;        ret = 1;    Goto leave; } message = NULL;     Leave:/* * Here is the exit * Wait for all Non-daemon threads to end and then destroy the VM. * This would actually create a trivial new Java waiter thread * named "DESTROYJAVAVM", but this would be seen as a Diffe  Rent * thread from the one, executed main, even though they is * the same C thread.     This allows mainthread.join () and * mainthread.isalive () to work as expected.    */(*VM)-&GT;DESTROYJAVAVM (VM);    if (Message! = NULL &&!noexiterrormessage) reporterrormessage (message, messagedest); return ret;


If you can Java, but not the JVM, but also can not understand the JVM, then to learn from the teacher GE The JVM course it. http://www.dataguru.cn/myclassnew.php?mod=new_basicforlesson&op=basic&lessonid=208

or Join QQ Group 397196583 , to discuss where the JVM can't see what it's going through.

In Java for so long, can you say the Java boot process? Don't blow it, take a look at

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.