Analysis of dynamic proxies for Java RMI and Java Dynamics Proxy

Source: Internet
Author: User

We are recently ready to learn about the module architecture of the Hadoop RFC, but this module uses relatively new knowledge of Java, such as RMI, dynamic proxies, and the newly added amount of NiO in jdk1.4. So I decided to take a moment to review the knowledge of the first 2 modules. This makes it easier to understand the RPC traffic for Hadoop. Java RMI and Proxy dynamic agent I will not talk, I mainly briefly cite two examples, analysis of his call steps, and then combine his source code, to achieve understanding, there will be a effect on it.

OK, first of all, say RMI, full name remote method Invoke is a form of RPC, but there is a less good point is that many of his things are too customizable, and there are language restrictions, currently only support Java direct RMI call. The core of RMI architecture is interface-oriented design. is the remote interface, any interface that needs to be called remotely must inherit from an remote interface, which is equivalent to a tag, similar to the Serializable interface. The following is an example of Hello World:

Package Com.unmi;import java.rmi.*;       /**    * Remote interface must extend interface Java.rmi.Remote */public   interface Hellointerface extends remote    {       /**       * The remote interface method must throw java.rmi.RemoteException       *      /Public String Say () throws remoteexception;    }

Then, the interface should be packaged in the form of objects;

Package Com.unmi;import java.rmi.*;    Import java.rmi.server.*;       /**    * extends the UnicastRemoteObject class and implements the remote interface Hellointerface */public   class Hello extends UnicastRemoteObject Implements Hellointerface    {       private String message;          /**       * Must define the constructor method, even if it is the default constructor, it must be explicitly written out, because it must throw out the RemoteException exception       *      /Public Hello (String msg) throws RemoteException       {          message = msg;       }          /**       * Remote interface method Implementation */Public      String say () throws RemoteException       {          System.out.println ("called by Helloclient ");          return message;       }    }

It then implements the RMI call by registering and locating the object on the naming.

         Start the RMI registration service, specify a port of 1099 (1099 is the default port)             ///can also be started by command $java_home/bin/rmiregistry 1099//             here in this way avoid opening a DOS window             again And with the command Rmiregistry start the registration service also must be in advance with rmic to generate a stub class for it to use             locateregistry.createregistry (1099);                        Create one or more instances of the remote object, the following is the Hello object             //can register different instances with different names             hellointerface hello = new Hello ("Hello, world!");                         Register Hello on the RMI registration server, named Hello             naming.rebind ("Hello", hello);    

The client only needs name.lookup ();

Hellointerface Hello = (hellointerface) naming.lookup ("Hello");                          If you want to find a hello instance on another machine that has the RMI registration service started             //hellointerface hello = (hellointerface) naming.lookup ("//192.168.1.105:1099 /hello ");                          Call the remote method             System.out.println (Hello.say ());    
Learn a module, we do not need to know how he is used, but also to know the details of the implementation, the following we have to peel the code inside, remote has just said that is similar to the Serializable interface there is no method and variable, Another key object is the UnicastRemoteObject.

public class UnicastRemoteObject extends RemoteServer {
Public abstract class RemoteServer extends RemoteObject
Public abstract class RemoteObject implements Remote, java.io.Serializable
Okay, in the end, so see here we know that the objects that are called remotely are serializable, and this interface has been inherited at the very bottom. The following is a general class relationship:




Here is an additional module, dynamic Proxy, the idea is reflected in many places, and very useful, the key lies in the characteristics of his Dynamic, perhaps some people will say, such a cost will sacrifice a lot of efficiency, this said is also true. But not the point in this article, but the key is how you weigh it. is also an example of a dynamic proxy, or HelloWorld, first defines an interface:

Public interface HelloWorld {       void SayHelloWorld ();}
Then define the specific implementation of an interface:

public class Helloworldimpl implements HelloWorld {public void SayHelloWorld () {System.out.println ("Hello world!");}}
A very important forwarding processor appears here:

public class HelloWorldHandler implements Invocationhandler {//The original object to be proxied with the private object objoriginal;/** * constructor. *  * @param obj *            The original object to be proxied. */public HelloWorldHandler (Object obj) {this.objoriginal = obj;} public object invoke (object proxy, Method method, object[] args) throws Throwable {Object result;//method call before Dobefore ();//Call Original The method of the Starting object result = Method.invoke (this.objoriginal, args);//After the method call Doafter (); return result;}
The invocation method in the scene class is also simple:

/** * Implementation of the Dynamic proxy class *  * @author lyq *  */public class Client {public static void main (string[] agrs) {HelloWorld HW = NE W Helloworldimpl (); Invocationhandler handler = new HelloWorldHandler (HW); HelloWorld proxy = (HelloWorld) proxy.newproxyinstance (Hw.getclass (). getClassLoader (), Hw.getclass (). Getinterfaces ( ), Handler);p Roxy.sayhelloworld ();}}
passed in the original class, and the processor,Get the dynamic proxy class, and finally call the method of the proxy class directly. The power of this approach is that you can do whatever you want before and after you do not know the method, such as entering the current time and so on. This is especially handy for logging logs. The test program output results are as follows:

Before Method invoke! Hello World!after Method invoke!
Or the key underlying design, the first is the mysterious Invocationhandler class:

Public interface Invocationhandler {public    object Invoke (Object Proxy, Method method, object[] args)        throws Thro wable;}
The principle is a interface ah. There is also a key to get the proxy class of Proxy.newintsance (), a look at this invocation form, we can guess that this must have a certain connection with reflection.

public static Object newproxyinstance (ClassLoader loader, class<?>[] Interf Aces, Invocationhandler H) throws IllegalArgumentException {if (h = = null)        {throw new NullPointerException ();        } final SecurityManager sm = System.getsecuritymanager ();        if (SM! = null) {checkproxyaccess (Reflection.getcallerclass (), loader, interfaces);         }/* * Look up or generate the designated proxy class.        */class<?> CL = GETPROXYCLASS0 (loader, interfaces);         /* * Invoke its constructor with the designated invocation handler.            */try {final constructor<?> cons = Cl.getconstructor (constructorparams);            Final Invocationhandler ih = h; if (SM! = null && Proxyaccesshelper.needsnewinstancecheck (CL)) {//Create proxy instance with DOPR IvileGE as the proxy class may//implement Non-public interfaces that requires a special permission                        Return accesscontroller.doprivileged (New privilegedaction<object> () {public Object run () {                    Return Newinstance (cons, IH);            }                });            } else {return newinstance (cons, IH);        }} catch (Nosuchmethodexception e) {throw new Internalerror (e.tostring ()); }    }
This uses a lot of construction classes and Class.forName () class loading methods, interested students can continue to trance code. I also made a structure at the end of the diagram:



Analysis of dynamic proxies for Java RMI and Java Dynamics Proxy

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.