Tomcat loading mechanism-How far can we go series (14)

Source: Internet
Author: User
How far can we go series (14)

Nonsense:Ladies and gentlemen, do you save your money? A colleague (female) got married a few days ago and learned about the situation: men and women buy a house close to 80 square meters, the actual house is 60 square meters, 400 thousands or 500 thousands of the down payment, plus decoration, family, I even paid for my grandparents and got married. Most of us will follow this path or already. I don't know how you feel when you hear such common gossip.

After reading the first two episodes of "WenZhou family", the buyer sent his daughter to study abroad and started his new life in Wenzhou with his son and wife. Although it was a TV series, we should all know that many of our previous generations had the same power. Yes, because at that time we were so poor, so we were so scared that we had nothing to do, if you lose, you still have nothing to worry about.

But now it's different. We can make a little effort to get enough food, pay more, and get close to the legendary well-off society. We are comfortable. We love comfort. Who wants to break it? No one wants. Therefore, we would rather bear huge mortgages, take over the blood and sweat of our parents, lose our dreams, and maintain the ease of living.

I don't know whether it is good or not. After all, I am not qualified to evaluate it. But this contradiction is what most of us are facing now. How can you be wise at it?

Bytes --------------------------------------------------------------------------------------

I used my lunch break to go to a company for an interview a few days ago. I have a question:How can we ensure that the module or method you write is of high quality?

I said at the time: Through unit testing, what review, performance testing.

Incorrect answer direction.

Readability:CodeWhether it is readable and easy to read. For a team, whether the encoding standards are consistent and whether the encoding styles are consistent;

Functionality: the code correctly implements the business logic;

Maintainability: the code logic is hierarchical and easy to modify;

Efficiency: code implementation is efficient in the use of time and space;

How do you answer this question?

Subject:

Peripheral knowledge:

1. For the basic principles of JVM (Java virtual mechanic) Load class, refer toArticle

2. About class. forname (string)
First, we understand that after the class file is loaded by JVM, it can be understood to exist in the memory in binary form. Every class can be found through the package name and class name.
Second, with the new operation, why do we still need it?
A piece of code on the Internet explains this problem:

String classname = readfromxmlconfig;//Obtain the string from the xml configuration fileClassC =Class. forname (classname); factory= (Exampleinterface) C. newinstance ();

We can see that the newinstance instance can be satisfied as long as it inherits the exampleinterface interface. Remember that if the provided class does not inherit exampleinterface, an exception will occur.
The difference between the New Keyword and the newinstance () method:
Newinstance: weak type. Low efficiency. Only construction without parameters can be called. (However, the code below seems to be able to construct parameters ...)
New: strong type. Relatively efficient. Can call any public constructor.

3. Load class java. Lang. classloader
We can call the loadclass (string) method of classloader to load the class we need.
Example:

 Package  Code. loader;  Import  Java.net. url;  Import Java.net. urlclassloader;  Import  Code. mytest. Test2;  Public   Class  Myloader1 {  Public   Static   Void Main (string [] ARGs) Throws  Exception {  //  Class Name (note: the package name is included in the form of No. Class) String classname = "code. mytest. Test2" ; //  Class File Location URL url = New URL ("file:/D :/" );  //  Classloader instance Classloader loader = New Urlclassloader ( New  URL [] {URL });  //  Load is a class instance. Class C1 = Loader. loadclass (classname );  // Use the class instance to get the desired instance Test2 test = (Test2) c1.newinstance ();  //  Method for calling a new instance  Test. sayyouily ();}} 

Tomcat load class:

Tomcat needs to load the servlet class in the web project by itself. When we frequently release the modified project, Tomcat needs to load the code we provide to let it run.
After the HTTP request enters tomcat, Tomcat needs to load the class according to the called servlet name. This process is implemented by the internal class of Tomcat: Org. apache. catalina. loader. webapploader implementation. This class implements Tomcat's org. apache. catalina. loader interface, while webapploader references Org. apache. catalina. loader. webappclassloader, while webappclassloader inherits urlclassloader

Webapploader uses the getclassloader () method to provide a custom classloader. Why? Let's look at the source code:
1. The start () method in webapploader calls the following two sentences:

Classloader = createclassloader ();//This is the built-in private method.Classloader. setresources (container. getresources ());

2. createclassloader source code:

 Private  Webappclassloader createclassloader ()  Throws  Exception {  //  What is this loaderclass?  //  It is actually a private variable of webappclassloader, defined as: Private string loaderclass = "org. Apache. Catalina. loader. webappclassloader "; Class clazz =Class. forname (loaderclass); webappclassloader classloader = Null  ;  If (Parentclassloader = Null  ) {Parentclassloader = Container. getparentclassloader ();} class [] argtypes = {Classloader. Class  }; Object [] ARGs = {Parentclassloader };  // API: returns a constructor object that reflects the specified public constructor of the Class Object. The parametertypes parameter is an array of class objects. These class objects identify the parameter type of the constructor in the declared order. Constructor constr = Clazz. getconstructor (argtypes );  //  Use the constructor object to create a new instance of the declared class of the constructor object and initialize the instance with the specified initialization parameter. (Does this achieve the parameter structure mentioned above) Classloader = (Webappclassloader) constr. newinstance (ARGs );  Return  Classloader ;} 

3. Through webappclassloader, you can control the loaded classes without repeated operations.
Every class loaded through webappclassloader is recorded by org. Apache. Catalina. loader. resourceentry.

 Package Org. Apache. Catalina. loader;  Import  Java.net. url;  Import  Java. Security. cert. Certificate;  Import  Java. util. Jar. manifest;  Public   Class  Resourceentry {  Public   Long Lastmodified =-1 ;  Public   Byte [] Binarycontent = Null ; //  Classes are stored in memory as byte arrays.      Public   Volatile Class loadedclass = Null  ;  Public URL source = Null ; //  URL name      Public URL codebase = Null  ; Public Manifest manifest = Null  ;  Public Certificate [] certificates = Null  ;} 

In webappclassloader, there is a map to record the loaded class.

 
 /*** The cache of resourceentry for classes and resources we have loaded, * keyed by resource name.*/ProtectedHashmap resourceentries =NewHashmap ();

In this way, when we need to load a new class, we will first find it in this map.
Let's take a look at the findresource method source code:

 Public URL findresource ( Final  String name ){  If  (Log. isdebugenabled () log. debug ( "Findresource (" + name + ")" ); URL = Null  ;  If (Hasexternalrepositories && Searchexternalfirst) URL = Super  . Findresource (name );  If (Url =Null  ){  //  Go to the memory to find whether it has been loaded Resourceentry entry = (Resourceentry) resourceentries. Get (name );  //  Not loaded              If (Entry = Null  ){  If (Securitymanager! = Null  ) {Privilegedaction <Resourceentry> dp = New  Privilegedfindresourcebyname (name, name); entry = Accesscontroller. doprivileged (DP );}  Else  {Entry = Findresourceinternal (name, name );}}  //  Loaded              If (Entry! = Null  ) {URL =Entry. Source ;}}  If (Url = Null ) & Hasexternalrepositories &&! Searchexternalfirst) URL = Super  . Findresource (name );  If  (Log. isdebugenabled ()){  If (URL! = Null  ) Log. debug ( "--> Returning '" + URL. tostring () + "'");  Else  Log. debug ( "--> Resource not found, returning null" );}  //  Return URL          Return  (URL );} 

 

Summary:

1. Tomcat customizes its own class loader, which is worth learning. We have not studied the core implementation classes yet, because we also need to learn the implementation of custom loader.

2. It is very practical to use hashmap to store resources that require real-time query.

 

Let's move on

----------------------------------------------------------------------

 

Hard work may fail, but not hard work will certainly fail.
Sharing

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.