Tomcat class loading

Source: Internet
Author: User
Tags tomcat server

Turn from: Http://www.tuicool.com/articles/NrI7NrN

Http://www.tuicool.com/articles/eQBJfyn

1. Start-up Process

Whether it's an operating system or an application, you have to start from scratch with a step-by-step startup process. Tomcat is no exception, and it's all starting from scratch. Embedding other applications is also supported by code launches in a new version of Tomcat, but this article has the most common command-line startup examples to start with.

We opened Tomcat's compressed package, which contained startup.sh scripts and a. bat file to support the Windows environment, where the mystery of Tomcat Kai-stop is here. In startup.sh, there is a sentence:

Exec "$PRGDIR"/"$EXECUTABLE" Start "$@"

The $executable is the catalina.sh that is assigned to the above, which means that the catalina.sh is executed, and the argument that follows is start, and we continue to look at the catalina.sh script, which has a line of open paragraphs:

elif ["$" = "start"]; Then

The final execution statement is:

Eval "\" $_runjava\ "" "\" $LOGGING _config\ "" $LOGGING _manager $JAVA _opts $CATALINA _opts \
      -djava.endorsed.dirs= "\" $JAVA _endorsed_dirs\ "-classpath" \ "$CLASSPATH" "\
      -dcatalina.base=" \ "$CATALINA _base\" "
      Dcatalina.home= "\" $CATALINA _home\ "" \
      -djava.io.tmpdir= "\" $CATALINA _tmpdir\ "" \
      Org.apache.catalina.startup.Bootstrap "$@" Start
      >> "$CATALINA _out" 2>&1 "&"

And $_runjava is the system environment of Java, ignore the middle of the parameters regardless, we can see that the startup Java class is org.apache.catalina.startup.Bootstrap.

_runjava= "$JRE _home"/bin/java

And this Org.apache.catalina.startup.Bootstrap class has a Main method, which is the same as the principle of compiling a HelloWorld class that we simply write directly.

Here, we can have a conclusion, in reading any system of source code, there will be an entrance, grasp the entrance to grasp everything. And any application running in Java will eventually have a public class and a main, which is absolute, although servlet development does not need attention, as long as the API programming can be, but even so ultimately through the servlet container to meet this point.

That's it, Tomcat started. 2. Bootstrap class

On the paperwork said Org.apache.catalina.startup.Bootstrap's main method was implemented. Find the corresponding Tomcat source code, we see that it can be divided into 2 blocks: static object daemon creation and initialization, according to the command line parameters to daemon call the corresponding method.

Look at the first piece, from the daemon declaration we can see that it is a bootstrap object, it needs to create a new one when it is null, and executes the init () method, which is initialized and assigned to daemon. Let's go a step further and see what the bootstrap init () method does.

public void Init () throws Exception {//Set Catalina path Setcatalinahome ();
        Setcatalinabase ();
        Initclassloaders ();
        Thread.CurrentThread (). Setcontextclassloader (Catalinaloader);

        Securityclassload.securityclassload (Catalinaloader); Load our startup class and call it process () method if (log.isdebugenabled ()) Log.debug ("Loading s
        Tartup class ");
        class<?> Startupclass = Catalinaloader.loadclass ("Org.apache.catalina.startup.Catalina");

        Object startupinstance = Startupclass.newinstance (); Set the Shared Extensions class loader if (log.isdebugenabled ()) Log.debug ("Setting startup class P
        Roperties ");
        String methodname = "Setparentclassloader";
        class<?> paramtypes[] = new CLASS[1];
        Paramtypes[0] = Class.forName ("Java.lang.ClassLoader");
        Object paramvalues[] = new OBJECT[1]; ParamValues[0] = Sharedloader;
        Method method = Startupinstance.getclass (). GetMethod (methodname, paramtypes);

        Method.invoke (Startupinstance, paramvalues);
    Catalinadaemon = startupinstance; }

And this method can be divided into two parts: the first 5 statements, to initialize the Catalina class loader-related environment variables, and then initialize the various class loader objects, including Commonloader, Sharedloader, The most important of these is catalinaloader, which is set to a property value of bootstrap. Starting with the sixth statement, use the Catalinaloader to load Tomcat's core object with the previous widget. That is the object Catalinadaemon of the Org.apache.catalina.startup.Catalina class and calls its Setparentclassloader method in reflection, passing sharedloader as a parameter.

We see in this process that the bootstrap class holds several objects (static daemon, non-static Catalinadaemon, Commonloader, Sharedloader, Catalinaloader) are both created and required for initialization.

So next we look at the second half of the main method. For example, just start, we get the command line argument is start, then the following code will be executed:

else if (command.equals ("start")) {
                daemon.setawait (true);
                Daemon.load (args);
                Daemon.start ();
            }

The setawait (), load (), and start () Three methods of the Daemon object of the bootstrap class are called separately. These three methods are slightly deeper and we find a call from the Bootstrap method to the Catalina method, and the middle is reflected. As for these 3 methods, the final concrete what to do, we do not elaborate here, the following will be divided into detailed finishing, but can be simple to understand, where: Setawait () is set the Catalina object of a property value, its role is to tell the server to start after the operation of the State, and open a specific port to listen for subsequent instructions, until received shutdown instructions, do shutdown server processing. Load () is loaded and initialized. Loads and resolves the configuration files associated with the entire Tomcat server, and initializes the configuration operations for each of Tomcat's components. Start (), which in fact does not have to say, is to officially start Catalina, or to start the core work of the Tomcat server.

Take this as an example, for bootstrap other commands, such as stop, this article does not want to describe in detail, interested in the way you can see the source code. 3. Tomcat class loading

Like other mainstream Java Web servers, Tomcat also has different custom classloader to control a variety of resource repositories. In general, the Java Web server needs to address the following four issues:

① the same Web server, the Java class libraries used by each Web project are isolated from each other.

② the same Web server, a shared Java class Library can be provided between individual Web projects.

③ servers in order to be unaffected by Web projects, you should make the server's class library independent of the application's class library.

④ for Web servers that support JSP, hot-swappable (hotswap) functionality should be supported.

For the above problems, if using a class loader alone is obviously not effective, you must use several custom class loaders based on the actual usage.

The following is an example of the Tomcat7 of the main analysis of this book to see how its classloader is defined. As shown in Figure 2-4-3, launch class loader, extended class loader, application class loader three class loader data JDK level loader, they are unique, we generally do not make any changes to it.  Next is the Tomcat ClassLoader, in Tomcat7, the most important class loader is common ClassLoader, its parent class loader is applicationclassloader, responsible for loading $CATALINA _base/lib, $CATALINA _home/lib all. Class and. jar files in two directories. The two class loaders of the following dashed boxes need to explain that, if in the TOMCAT5 version, the two class loader instances default to Common ClassLoader instances, Common ClassLoader to their parent class loader. And in Tomcat7, these two instance variables also exist, Only the Catalina.properties configuration file does not configure Server.loader with Share.loader two, so in the program, the two ClassLoader instances are assigned to the Commonclassloader instance, that is, a Tomcat instance actually has only com Monclassloader instance. such as the following code

private void Initclassloaders () { try {

Commonloader = Createclassloader ("common", null);

if (Commonloader = = null) {

Commonloader = this. GetClass (). getClassLoader ();

}

Catalinaloader = Createclassloader ("server", Commonloader);

Sharedloader = Createclassloader ("Shared", Commonloader);

catch (Throwable t) {

Handlethrowable (t);

Log. Error ("Class loader creation threwexception", t);

System. Exit (1);

}

}

First create a commonloader, and then pass the Commonloader as a parameter into the Createclassloader method, In this method, a new ClassLoader is created based on whether the Server.loader and Share.loader properties in Catalina.properties are empty, and if the property is empty, the Commonloader is directly assigned to Catalinaloader and S. Haredloader. If the default configuration does not meet your needs, you can modify the Catalina.properties configuration file to meet your needs. WebappClassLoader from the name is probably known primarily for loading Web applications, its parent class loader is common ClassLoader, typically has multiple WebApp class loader instances, each loader loads a Web program, loading path to/ Webapp/web-inf directory. Finally, the JSP ClassLoader is responsible for loading the JSP file compiled Class,webapp ClassLoader for its parent class loader, when Tomcat detects a change in the JSP file, will create a new JSP ClassLoader and replace the current JSP Classlassloader, the/webapp/web-inf directory to load the JSP.

Figure 2-4-3 TOMCAT7 Class Loader

In contrast to a class loader structure like this, look at the problems that the Java Web server needs to address above. Because each Web application project has its own WebApp ClassLoader, it makes it easy to isolate multiple Web applications and effectively makes Tomcat unaffected by Web applications; Common The existence of ClassLoader enables multiple Web applications to share class libraries with each other, and each JSP file corresponds to a JSP classloader that enables Tomcat to support hot-swap functionality.

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.