Proxy mode for Java program performance optimization

Source: Internet
Author: User

Proxy mode for Java program performance optimization
The proxy mode is widely used, for system security and for remote calls. Here we mainly discuss the delay Loading Caused by program performance optimization. First, let's take a look at the proxy pattern design. First, let's briefly describe what proxy pattern is. The proxy design pattern has an interface. In addition, there are real themes and proxies. both real and proxy classes implement interfaces, the proxy class and the real topic class are associated and aggregated. The client is associated with the interface. The agent is divided into static proxy and dynamic proxy. The so-called static proxy is to manually create a proxy for the real topic, while dynamic proxy is to automatically create a proxy using the bytecode loading technology when jvm is running, don't worry about how interfaces and theme classes are implemented. How the proxy mode optimizes the program? Let's take a look at it. The client test code is as follows:

public class TestDynamicProxy {        public static void main(String[] args) {                     IDBQuery iy = JdkDBqueryHandler.createJdkProxy();            System.out.println(iy.request());                 }} 

 

Ps: the client-interface-related proxy implementation and logic processing class are as follows:
import java.lang.reflect.*;    public class JdkDBqueryHandler implements InvocationHandler{            IDBQuery real = null;            public Object invoke(Object object, Method method ,Object[] args ) {                if(real==null) {                                     real = new DBQuery();                }                return real.request();                             }    public static IDBQuery createJdkProxy() {                IDBQuery jdkProxy = (IDBQuery)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),new Class[]{IDBQuery.class},new JdkDBqueryHandler());                return jdkProxy;            }  }

 

Ps: The agent implementation and logic processing class are the key code for implementing delayed loading. When the client starts loading, the code implementation and logic processing class will be loaded and the proxy instance will be created, however, the actual topic category is not initialized. Only when the iy. request () method is called will the invoke () method of the proxy implementation and logic processing class be executed and loaded and the real topic class be initialized. In this way, delayed loading is realized, the system initialization time is reduced, and the user experience is improved. To a certain extent, it can also save memory space and avoid memory space waste (because Initialization is recorded only when used, and it is not a waste if you don't need to open up memory space) the code of the Interface Class and the real topic class is attached to facilitate testing of the interface class.
public interface  IDBQuery {       String request();}

 

Real themes
public class  DBQuery implements IDBQuery {                 public DBQuery() {                try{                           Thread.sleep(1000);                                         }catch(InterruptedException e) {                                         e.printStackTrace();                }                 }        public String request() {                          return "request coming";                 }      }

 

The above is the built-in dynamic proxy Implementation of jdk, and the popular CGLIB dynamic proxy, javaassist dynamic proxy here I will first introduce CGLIB dynamic proxy. CGLIB dynamic proxy is very similar to jdk dynamic proxy. The specific code client code is as follows:
public class TestDynamicProxy {        public static void main(String[] args) {                     IDBQuery iy = CglibDbQueryInterceptor.createCglibProxy();            System.out.println(iy.request());                 }}

 

I have explained more here. After reading the above examples, I believe everyone understands the following types of proxy implementation and logical processing:
Import java. lang. reflect. method; import net. sf. cglib. proxy. enhancer; import net. sf. cglib. proxy. methodInterceptor; import net. sf. cglib. proxy. methodProxy; public class CglibDbQueryInterceptor implements MethodInterceptor {IDBQuery real = null; public Object intercept (Object args0, Method arg1, Object [] args2, MethodProxy args3) throws Throwable {if (real = null) {real = new DBQuery ();} return real. request ();} public static IDBQuery createCglibProxy () {Enhancer eh = new Enhancer (); eh. setCallback (new CglibDbQueryInterceptor (); // specify the inceptor and define the logic of the proxy class eh. setInterfaces (new Class [] {IDBQuery. class}); // specify the interface IDBQuery proxy = (IDBQuery) eh. create (); // create proxy instance return proxy ;}}

 

The dynamic proxy and CGLIB of Jdk must both specify the agent logic and the proxy interface. This is the same as the real topic category and interface in the previous example, there are two implementation methods for dynamic proxy that no longer sticks to JavaAssist. One is to use the proxy factory, and the other is to use dynamic java code to generate bytecode. The code is directly pasted here: image Upload Failed ~~~ Ps: The above instance methods are processed in the logic processing class. The real topic class and interface are the same as the preceding example. The proxy factory specifies the interface and generates the proxy class object. The proxy class object then specifies the processing logic. Generally, the three are similar. javaAssist is not introduced when dynamic java code is used to generate bytecode. It is difficult to catch up with others.

Related Article

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.