How Tomcat works Reading Notes 8 Loader

Source: Internet
Author: User

Java Class Loader

For more information, see

Http://blog.csdn.net/dlf123321/article/details/39957175

Http://blog.csdn.net/dlf123321/article/details/40431297

Two terms are described first.
Repository (repository), indicating where the class loader will search for the class to be loaded;
Resource, which knows the dircontext object in the class loader. Its file and path refer to the context file and path.
In tomcat, we use a custom loader for three reasons:
To specify certain rules in the loader;
To Cache loaded classes;
To implement class pre-loading;

When loading servlets and related classes, the loader interface must comply with some rules. For example, the servelt in an application can only reference classes deployed in the Web-INF/classes directory and Its subdirectories, and can only access libraries under the web-INF/lib directory.
The loader we mentioned in Tomcat refers to the Web Application Loader, not just the class loader. (The loader contains a Class Loader !!!)
The loader should implement the org. Apache. Catalina. loader interface. The default class loader is webappclassloader.
Package Org. apache. catalina; import Java. beans. propertychangelistener; public interface loader {public classloader getclassloader (); Public container getcontainer (); // The loader is usually associated with a context-level container public void setcontainer (container ); public defaultcontext getdefacontext context (); Public void setdefaultcontext (defaultcontext); Public Boolean getdelegate (); // delegate indicates delegate public void setdelegate (Boolean delegate ); // whether the Class Loader delegates the loaded task to its parent class loader Public String getinfo (); Public Boolean getreloadable (); // indicates whether auto-Reload public void setreloadable (Boolean reloadable); Public void addpropertychangelistener (propertychangelistener listener); Public void addrepository (string repository ); public String [] findrepositories (); Public Boolean modified (); // if one or more classes in the container are modified with modified, true public void removepropertychangelistener (propertychangelistenerlistener) is returned );}

By default, the standard implementation of context --- Org. apache. catalina. core. standcontext does not support Automatic Reload. Therefore, to enable the automatic reload function, you must. add a context element to the XML file as follows:
<Context Path = "/MyApp" docbase = "MyApp" DEBUG = "0" reloadable = "true"/>
In our program in this section, Catalina provides org. Apache. Catalina. loader. webapploader as the implementation of the load interface. The webapploader object contains an instance of the org. Apache. Catalina. loader. webappclassloader class, which extends the java. neturlclassloader class.
When a container associated with a loader needs to use a servlet or call a method of a servlet, the container first calls the getclassloader () of the loader () the method returns the class loader, and then calls the loadclass () method of the class loader to load the servlet class.
The UML diagram is as follows:

When the start method of the webapploader class is started, the webapploader class performs the following tasks:
1. Create a Class Loader
2. Set the Repository
3. Set the class path
4. Set Access Permissions
5. Start a new thread to support automatic overloading (in the webapploader run method)

Create a Class Loader
Private webappclassloader createclassloader () throws exception {// loadclass is a string // The default value is private string loaderclass = "org. apache. catalina. loader. webappclassloader "; // you can use the setloadclass method to change the class <?> Clazz = Class. forname (loaderclass); webappclassloader classloader = NULL; // when constructing webapploader, specify if (parentclassloader = NULL) as the constructor parameter) {// will cause a classcast is the class does not extend WCL, but // This is on purpose (the exception will be caught and rethrown) classloader = (webappclassloader) clazz. newinstance ();} else {class <?> [] Argtypes = {classloader. Class}; object [] ARGs = {parentclassloader}; constructor <?> Constr = clazz. getconstructor (argtypes); classloader = (webappclassloader) constr. newinstance (ARGs);} return classloader ;}

Of course, we can use setloadclass to change the implementation of the Class Loader,
(Webappclassloader) constr. newinstance (ARGs );
Therefore, our custom classes must inherit webappclassloader.

Set repositories to call setrepositories, set the WEB-ING/classes directory with the WEB-INF/lib directory

Setting the class path is related to the Jasper JSP compiler.

Setpermissions allows the class loader to access related paths. For example, only the web-INF/classes directory and the WEB-INF/lib directory can be accessed.

Enable re-loading of New thread execution class
Public void run () {If (debug> = 1) log ("background thread starting "); // loop until the termination semaphore is set // The entire code segment is included in the while loop // threaddone has been set to false before // until the program is closed, threaddone will become true while (! Threaddone) {// wait for our check interval threadsleep (); If (! Started) break; try {// perform our modification check if (! Classloader. modified () continue;} catch (exception e) {log (SM. getstring ("webapploader. failmodifiedcheck "), e); continue;} // handle a need for reloading policycontext (); break;} If (debug> = 1) log ("background thread stopping");} private void threadsleep () {// specify try {thread to sleep the program for a period of time by checkinterval. sleep (checkinterval * 1000l);} catch (interruptedexception e ){;}}

Checkinterval: checks whether the classes in the container have been changed every several seconds!
If classloader. Modified () is changed, true is returned, and policycontext () is called directly ();
 private void notifyContext() {        WebappContextNotifier notifier = new WebappContextNotifier();        (new Thread(notifier)).start();    }protected class WebappContextNotifier implements Runnable {        /**         * Perform the requested notification.         */        public void run() {            ((Context) container).reload();        }    }
Webappcontextnotifier is the internal class of webapploader.
Here, a new thread is restarted to avoid congestion.

The webappclassloader class inherits from the java.net. urlclassloader class, which we have used in the previous chapter;
The design of the webappclassloader class takes security and optimization into account.
The webappclassloader class does not allow certain classes to be loaded. These classes are stored in an array of the string type, and now there is only one member.
Private Static final string [] triggers = {
"Javax. servlet. servlet" // servlet API
};
In addition, the class or its sub-package of some special packages cannot be loaded when it is assigned to the system loader:
private static final String[] packageTriggers = {    "javax", // Java extensions    "org.xml.sax", // SAX 1 & 2    "org.w3c.dom", // DOM 1 & 2    "org.apache.xerces", // Xerces 1 & 2    "org.apache.xalan" // Xalan};
Class Cache

To achieve better performance, the loaded classes will be cached, so that the next time you use this class, you do not need to load it again.

The cache is executed locally at two levels and managed by the webappclassloader instance.
In addition, the Java. Lang. classloader class will maintain a vector object and save the loaded class. At this time, the cache is managed by the parent class.

Each class loaded by webappclassloader is considered a resource. It is an instance of the org. Apache. Catalina. loader. resourceentry class, which contains the byte stream of the class file, the last modification time, and so on:
package org.apache.catalina.loader;import java.net.URL;import java.security.cert.Certificate;import java.util.jar.Manifest;public class ResourceEntry {    public long lastModifled = -1;    // Binary content of the resource.public byte[] binaryContent = null;    public Class loadedClass = null;    // URL source from where the object was loaded.    public URL source = null;    // URL of the codebase from where the object was loaded.    public URL CodeBase = null;    public Manifest manifest = null;    public Certificate[] certificates = null;}


All cached sources are stored in a hashmap called resourceentries. The key value is the name of the loaded resource. All the unfound resources are placed in a hashmap named notfoundresources.



As for the real loading class, we will talk about it in the next section.


Reference http://my.oschina.net/xianggao/blog/70826

How Tomcat works Reading Notes 8 Loader

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.