Performance optimization of the Java reflection mechanism

Source: Internet
Author: User

Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;ImportJava.util.HashMap;ImportJava.util.Map;ImportOrg.apache.log4j.Logger; Public classDynamicserver {Private StaticLogger log = Logger.getlogger (dynamicserver.class);  Public StaticMap<string,class> Clazzmap =NewHashmap<string,class>();  Public StaticMap<string,object> Objmap =NewHashmap<string,object>();  Public StaticMap<string,method> Metmap =NewHashmap<string,method>();  Public StaticMap<string,map<string,string>> Typemap =NewHashmap<string,map<string,string>>(); /*** Efficient invocation of a method within a class by reflection + cache **/     Public StaticObject cacheexce (String clazz,string method,object[] os,class[] CS)throwsnosuchmethodexception{Try {                intSize = 0; if(cs!=NULL) {size=cs.length; } Method M= Metmap.get (clazz+ "_" +method+ "_" +size);//The method used to differentiate the overloaded Object obj=Objmap.get (Clazz); if(m==NULL|| obj==NULL) {Class cl=Clazzmap.get (Clazz); if(cl==NULL) {CL=Class.forName (Clazz); Clazzmap.put (Clazz, CL);//Cache class object}if(obj==NULL) {obj=cl.newinstance (); Objmap.put (Clazz, obj);//Cache object instance}if(m==NULL) {m=Cl.getmethod (method, CS); Metmap.put (Clazz+ "_" +method+ "_" +size, m);//Cache Method object}}returnm.invoke (obj, OS);//dynamic invocation of the public declaration method in an object}Catch(Exception e) {e.printstacktrace (); Throw Newnosuchmethodexception (); }        }            /*** Get the return type of the specified method within the specified class by reflection + cache **/     Public StaticString CacheType (String clazz,string method)throwsclassnotfoundexception{Map<String,String> Clazzs =Typemap.get (Clazz); if(clazzs==NULL) {Map<String,String> mmap =NewHashmap<string, string>(); Class CL=Class.forName (Clazz); Method[] Ms=cl.getmethods ();//Get all the public methods inside a class for(method M:ms) {Mmap.put (M.getname (), M.getgenericreturntype (). toString ());//Traversal of all methods, the method name and return type exist in a static map (cache)} Clazzs=mmap;        Typemap.put (Clazz, mmap); }        returnClazzs.get (method); }    }

The code section should have nothing to say, the note has been written very clearly, the rest of the need to refer to the JDK documentation. So now it's time to pull out the technical topics outside of the code.

One, nine events, one person a week

This is actually the case. My new company, is to do operational support for telecommunications, every holiday will do some send traffic to send the charges. This time, is for the August Rio Olympic Games, to Xinjiang over there to do nine activities, what Olympic swimming, Olympic shooting and so on, anyway, nine.

Originally, this is a bit of a relationship with me, but then a little accident, and from the line to more than a week more time, nine activities have been developed almost nearly, suddenly received the notice of the superior to open an emergency meeting, said the activities need rectification,, said the production environment for safety reasons, Web applications cannot access the database directly, and the database needs to be placed on the intranet server. The current solution is to develop an intranet application specifically for database read and write operations, and then provide external interfaces for Web application access. Then the leader then said to me, now the majority of the company is engaged in this period of activities, are not able to spare time, there are a few novice, also not very reassuring them to get, so this arduous task to you, a week can be done? And then I said yes, yes, yes.

After the class, suddenly feel something wrong! A week!!! Nine active data read and write operations!! A moment of collapse, a week is not enough I understand the needs of nine business activities. So hurriedly to find the leader to ask can be resolved by other means, such as in the outermost add a reverse proxy server to do a request to forward something, so you do not have to change the code. But the leader's reply is not good. All right, just admit it.

Second, why use reflection

The next day, I inquired about the situation of the colleagues who were involved in the development of the event. At first it was a little out of the way, and then someone proposed to have them provide SQL, which would greatly reduce my workload. Then I asked, and found that most of the activities were written in jfinal, so that I could directly copy their DAO layer files directly. The next thing to do is write the interface, which corresponds to method one by one. So the new problem came, each activity, database read and write at least 15 methods above, and each method passed the parameters are not the same, the development of the time also did not consider the problem of integration, so there is no inheritance, what polymorphic. This means that I have to write close to 200 ways to correspond with each one, for me, this is the biggest disaster since writing code! Tell me, in this case, what else can I do besides using reflection? Want me to code 200 method, simply let me go to shi ...

Third, the performance is worrying

After three days, counting the lines and moving the bricks, the accumulation of no more than 800 lines of code ended the disaster. For the next few days, I tuned in with a couple of development activities and then hurried online. The test feels OK, but after the launch, it feels like the activity opens the special card. Then our company to check the performance of the server, found that the deployment of the backend interface server CPU utilization rate soared to more than 90%. Damn, disaster again, must be the program problem, prior to understand the JVM performance monitoring some knowledge, and then Baidu a bit using the Jstack command to print out the stack information analysis is that part of the code problem. However, the stack of information is printed out, but it is completely not understood (hope to have a big God pointing out). There is no way to finally have a piece of code, a piece of code measured (feel there should be a better way). Although the method is a bit stupid, but finally did not expect to find the murderer, the original is the reflection part of the code.

Four, the road of optimization

Baidu a bit, found in the load class, there is a way to find and execute the time is very resource. Thought for a while, think can be a few more resources to cache the operation, so that only in a call to this method at the time of the cost of resources, and in addition to the implementation of the Method.invoke method, other than the better resource parameters, can be directly from the cache Central, should be able to alleviate some of the pressure bar. It is better to dry up than to be useless. After the test, the execution time is nearly 10 times times faster than the original, and the same method calls the more times, the more can feel the gap.

Now the project has been online for some time, basically no matter what I did. Take an empty share of the work experience of that period of time, by the way, in the case of large concurrency, can not reflect as far as possible without! Also, who told me, in this case, in addition to using reflection, what can I do???

Performance optimization of the Java reflection mechanism

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.