Remote Method Invocation

The most fundamental means of communication in Java is method invocation. Mechanisms such as the Java event model are built on simple method invocations between objects in the same virtual machine. Therefore, when we want to communicate between virtual machines on different hosts, it's natural to want a mechanism with similar capabilities and semantics. Java's RMI mechanism does just that. It lets us get a reference to an object on a remote host and use it almost as if it were in our own virtual machine. RMI lets us invoke methods on remote objects, passing real Java objects as arguments and getting real Java objects as returned values. Remote invocation is nothing new. For many years, C programmers have used remote procedure calls (RPC) to execute a C function on a remote host and return the results. The primary difference between RPC and RMI is that RPC, an offshoot of the C language, is primarily concerned with data structures. It's relatively easy to pack up data and ship it around, but for Java, that's not enough. In Java we don't just work with data structures; we work with objects that contain both data and methods for operating on the data. Not only do we have to be able to ship the state of an object (the data) over the wire, but the recipient has to be able to interact with the object (use its methods) after receiving it. With Java RMI, you can work with network services in an object-oriented fashion, using real, extensible types and pass "live" references between client and server. It should be no surprise that RMI uses object serialization, which allows us to send graphs of objects (objects and all the connected objects that they reference). When necessary, RMI can also use dynamic class loading and the security manager to transport Java classes safely. In addition to making remote method calls almost as easy to use as local calls, RMI makes it possible to ship both data and behavior (code) around the Net.

Remote and Nonremote Objects

Before an object can be used remotely through RMI, it must be serializable. But that's not sufficient. Remote objects in RMI are real distributed objects. As the name suggests, a remote object can be an object on a different machine or an object on the local host. The term remote means that the object is used through a special kind of object interface that can be passed over the network. Like normal Java objects, remote objects are passed by reference. Regardless of where the reference is used, the method invocation occurs on the original object, which still lives on its original host. If a remote host returns a reference to one of its remote objects to you, you can call the object's methods; the actual method invocations happen on the remote host, where the object resides. Nonremote objects are simpler; they're just normal serializable objects. (You can pass these over the network as we did in the previous section.) The catch is that when you pass a nonremote object over the network, it is simply copied, so references to the object on one host are not the same as those on the remote host. Nonremote objects are passed by value (copying) as opposed to by reference. This may be acceptable for many kinds of data holder objects on your host, such as the client requests and server responses in our previous example. These types of objects are sometimes called value objects or data transfer objects (DTOs).

Stubs and skeletons (be gone!)

No, we're not talking about a gruesome horror movie. Stubs and skeletons are used in the implementation of remote objects. When you invoke a method on a remote object (which could be on a different host), you are actually calling some local code behind the scenes that serves as a proxy for that object. This is the stub. (It is called a stub because it is something like a truncated placeholder for the object.) The skeleton is another proxy that lives with the real object on its original host. It receives remote method invocations from the stub and passes them to the object. Prior to Java 5.0, it was necessary to explicitly generate the stub and skeleton classes for your remote objects and to deploy these classes with the corresponding parts of your app. If you are using only Java 5.0 clients and servers, you don't have to worry about that any longer, as Java now takes care of everything dynamically for you at runtime. If you're using an older version of Java or require interoperability with older Java clients, you must still generate these classes as part of your build process. It's not a big deal and your code never has to reference them directly; they are hidden from you (in the closet, so to speak). Stubs and skeletons for your remote objects are created by running the rmic (RMI compiler) utility. After compiling your Java source files normally, you run rmic on the remote object classes as a second pass. It's easy; we'll show you how in the following examples.

Remote interfaces

Remote objects implement a special remote interface that specifies which of the object's methods can be invoked remotely. The remote interface is part of your app that you create by extending the java.rmi.Remote interface. Your remote object then implements its remote interface as it would any other Java interface. In your client-side code, you should then refer to the remote object as an instance of the remote interfacenot as an instance of its implementation class. Because both the real object and stub that the client receives implement the remote interface, they are equivalent as far as we are concerned (for method invocation); locally, we never have to worry about whether we have a reference to a stub or to an actual object. This type equivalence means that we can use normal language features such as casting with remote objects. Of course, public fields (variables) of the remote object are not accessible through an interface, so you must make accessor methods if you want to manipulate the remote object's fields. One additional requirement for remote objects distinguishes them from local objects. All methods in the remote interface must declare that they can throw the exception java.rmi.RemoteException. This exception (or one of its subclasses) is thrown when any kind of networking error happens (for example, a server crash, a network failure, or timeout). Some people see this as a limitation and try to paper over it in various ways. However, the RemoteException is there for a reasonremote objects can behave differently from local objects and your code needs to deal with that issue explicitly. There is no magic bullet (automatic retries, transactions) that truly makes the difference go away. Here's a simple example of the remote interface that defines the behavior of RemoteObject; we give it two methods that can be invoked remotely, both of which return some kind of Value object:

 import java.rmi.*;
 public interface RemoteObject extends Remote {
 public Value doSomething( ) throws RemoteException;
 public Value doSomethingElse( ) throws RemoteException;
 }


Exporting remote objects

You make a remote object available to the outside world by using the java.rmi.server.UnicastRemoteObject class. One way is simply to have the implementation of your remote object extend UnicastRemoteObject. When a subclass of UnicastRemoteObject is constructed, the RMI runtime system automatically "exports" it to start listening for network connections from clients. Like java.lang.Object, this superclass also provides implementations of equals( ), hashcode( ), and toString( ) that make sense for a remote object. Here's a remote object class that implements the RemoteObject interface we showed earlier and extends UnicastRemoteObject; we haven't shown implementations for the two methods or the constructor:

 public class MyRemoteObject implements RemoteObject
 extends java.rmi.UnicastRemoteObject
 {
 public MyRemoteObject( ) throws RemoteException {...}
 public Value doSomething( ) throws RemoteException {...}
 public Value doSomethingElse( ) throws RemoteException {...}
 // nonremote methods
 private void doSomethingInternal( ) { ... }
 }


Note that we have to supply a constructor that can throw a RemoteException (even if it does nothing) because UnicastRemoteObject's default constructor throws RemoteException and, even if it's not shown, the Java language always delegates to the superclass constructor. This class can have as many additional methods as it needs (presumably most of them will be private, but that isn't strictly necessary) but these nonremote methods are not required to throw the remote exception. Now, what if we can't or don't want to make our remote object implementation a subclass of UnicastRemoteObject? Suppose, for example, that it has to be a subclass of BankAccount or some other special base type for our system. Well, we can simply take over the job of exporting the object ourselves, using the static method exportObject( ) of UnicastRemoteObject. The exportObject( ) method takes as an argument a Remote interface and accomplishes what the UnicastRemoteObject constructor normally does for us. It returns as a value the remote object's client stub. However, you will normally not do anything with this directly. In the next section, we'll discuss how clients actually find your service, through the RMI registry (a lookup service). Normally, exported objects listen on individual ephemeral (randomly assigned) port numbers by default. (This is implementation-dependent.) You can control the port number allocation explicitly by exporting your objects using another form of UnicastRemoteObject.exportObject( ), which takes both a Remote interface and a port number as arguments. Finally, the name UnicastRemoteObject begs the question, "What other kinds of remote objects are there?" Right now, none. It's possible that Java could add remote objects using other protocols or multicast techniques in the future.

The RMI registry

The registry is RMI's phone tutorial. You use the registry to look up a reference to a registered remote object on another host, using an app-specified name. We've already described how remote references can be passed back and forth by remote method calls. The registry is needed to bootstrap the process; the client needs some way of looking up an initial object. The registry is implemented by a class called Naming and an app called rmiregistry. The rmiregistry app must be running on the local host before you start a Java program that uses the registry. You can then create instances of remote objects and bind them to particular names in the registry. A registry name can be anything you choose; it takes the form of a slash-separated path. When a client object wants to find your object, it constructs a special URL with the rmi: protocol, the hostname, and the object name. On the client, the RMI Naming class then talks to the registry and returns the remote object reference. So, which objects need to register themselves with the registry? Initially this can be any object the client has no other way of finding. But a call to a remote method can return another remote object without using the registry. Likewise, a call to a remote method can have another remote object as its argument, without requiring the registry. You could design your system such that only one object registers itself and then serves as a factory for any other remote objects you need. In other words, it wouldn't be hard to build a simple object request "bouncer" (we won't say "broker") that returns references to all the remote objects your app uses. Depending on how you structure your app, this may happen naturally anyway. The RMI registry is just one implementation of a lookup mechanism for remote objects. It is not very sophisticated, and lookups tend to be slow. It is not intended to be a general-purpose directory service but simply to bootstrap RMI communications. More generally, the Java Naming and Directory Interface (JNDI) can be used as a front end to other name services that can provide this functionality. JNDI is used with RMI as part of the Enterprise JavaBeans APIs.

An RMI Example

In our first example using RMI, we duplicate the simple serialized object protocol from the previous section. We make a remote RMI object called MyServer on which we can invoke methods to get a Date object or execute a WorkRequest object. First, we define our Remote interface:

 //file: ServerRemote.java
 import java.rmi.*;
 import java.util.*;
  
 public interface ServerRemote extends Remote {
 Date getDate( ) throws RemoteException;
 Object execute( WorkRequest work ) throws RemoteException;
 }


The ServerRemote interface extends the java.rmi.Remote interface, which identifies objects that implement it as remote objects. We supply two methods that take the place of our old protocol: getdate( ) and execute( ). Next, we implement this interface in a class called MyServer that defines the bodies of these methods. (Note that a more common convention for naming the implementation of remote interfaces is to append Impl to the class name. Using that convention, MyServer would instead be named something like ServerImpl.)

 //file: MyServer.java
 import java.rmi.*;
 import java.util.*;
 public class MyServer
 extends java.rmi.server.UnicastRemoteObject
 implements ServerRemote {
 public MyServer( ) throws RemoteException { }
 // implement the ServerRemote interface
 public Date getDate( ) throws RemoteException {
 return new Date( );
 }
 public Object execute( WorkRequest work )
 throws RemoteException {
 return work.execute( );
 }
  
 public static void main(String args[]) {
 try {
 ServerRemote server = new MyServer( );
 Naming.rebind("NiftyServer", server);
 } catch (java.io.IOException e) {
 // problem registering server
 }
 }
 }


MyServer extends UnicastRemoteObject, so when we create an instance of MyServer, it is automatically exported and starts listening to the network. We start by providing a constructor, which must throw RemoteException, accommodating errors that might occur in exporting an instance. Next, MyServer implements the methods of the remote interface ServerRemote. These methods are straightforward. The last method in this class is main( ). This method lets the object set itself up as a server. main( ) creates an instance of the MyServer object and then calls the static method Naming.rebind( ) to place the object in the registry. The arguments to rebind( ) include the name of the remote object in the registry (NiftyServer)which clients use to look up the objectand a reference to the server object itself. We could have called bind( ) instead, but rebind( ) handles the case where there's already a NiftyServer registered by replacing it. We wouldn't need the main( ) method or this Naming business if we weren't expecting clients to use the registry to find the server. That is, we could omit main( ) and still use this object as a remote object. We would just be limited to passing the object in method invocations or returning it from method invocationsbut that could be part of a factory registry, as we discussed before. Now we need our client:

 //file: MyClient.java
 import java.rmi.*;
 import java.util.*;
 public class MyClient {
  
 public static void main(String [] args)
 throws RemoteException {
 new MyClient( args[0] );
 }
  
 public MyClient(String host) {
 try {
 ServerRemote server = (ServerRemote)
 Naming.lookup("rmi://"+host+"/NiftyServer");
 System.out.println( server.getDate( ) );
 System.out.println(
 server.execute( new MyCalculation(2) ) );
 } catch (java.io.IOException e) {
 // I/O Error or bad URL
 } catch (NotBoundException e) {
 // NiftyServer isn't registered
 }
 }
 }


When we run MyClient, we pass it the hostname of the server on which the registry is running. The main( ) method creates an instance of the MyClient object, passing the hostname from the command line as an argument to the constructor. The constructor for MyClient uses the hostname to construct a URL for the object. The URL looks like this: rmi://hostname/NiftyServer. (Remember, NiftyServer is the name under which we registered our ServerRemote.) We pass the URL to the static Naming.lookup( ) method. If all goes well, we get back a reference to a ServerRemote (the remote interface). The registry has no idea what kind of object it will return; lookup( ) therefore returns an Object, which we must cast to ServerRemote, the remote interface type.

Running the example

If you're using Java 5.0, all you have to do is compile your code and you're ready to go. You can run the client and server on the same machine or on different machines. First, make sure all the classes are in your classpath (or the current directory if there is no classpath) and then start the rmiregistry and MyServer on your server host:

 % rmiregistry &   (on Windows: start rmiregistry  )
 % java MyServer 


Next, run the client, passing the name of the server host (or "localhost"):

 % java MyClient myhost


The client should print the date and the number 4, which the server graciously calculated. Hooray! With just a few lines of code, you have created a powerful client/server app. If you are using an earlier version of Java or wish to explicitly generate the client stub, you just have to take an extra step after compiling the code. Run the rmic app to make the stub and skeleton files for MyServer:

 % rmic MyServer


You should see some additional classes generated. Make sure these are deployed on both the client and server machines' classpaths; read on to learn about an alternative to distributing the classes on both client and server.

Dynamic class loading

Before running the example, we told you to distribute all the class files to both the client and server machines. However, RMI was designed to ship classes, in addition to data, around the network; you shouldn't have to distribute all the classes in advance. Let's go a step further and have RMI load classes for us as needed. This involves several steps. First, we need to tell RMI where to find any other classes it needs. We can use the system property java.rmi.server.codebase to specify a URL on a web server (or FTP server) when we run our client or server. This URL specifies the location of a JAR file or a base directory where RMI begins its search for classes. When RMI sends a serialized object (i.e., an object's data) to some client, it also sends this URL. If the recipient needs the class file in addition to the data, it fetches the file at the specified URL. In addition to stub classes, other classes referenced by remote objects in the app can be loaded dynamically. Therefore, we don't have to distribute many class files to the client; we can let the client download them as necessary. In Screenshot-3, we see an example of MyClient going to the registry to get a reference to the ServerRemote object. Once there MyClient dynamically downloads the stub class for MyServer from a web server running on the server object's host. We can now split our class files more logically between the server and client machines. For example, we could withhold the MyCalculation class from the server since it really belongs to the client. Instead, we can make the MyCalculation class available via a web server on some machine (probably our client's) and specify the URL when we run MyClient:

 % java -Djava.rmi.server.codebase='http://myserver/foo/' ...


The trailing slash in the codebase URL is important: it says that the location is a base directory that contains the class files. In this case, we would expect that MyCalculation would be accessible at the URL http://myserver/foo/MyCalculation.class. Next, we have to set up security. Since we are loading class files over the network and executing their methods, we must have a security manager in place to restrict the kinds of things those classes may do, at least when they are not coming from a trusted code source. RMI will not load any classes dynamically unless a security manager is installed. One easy way to meet this condition is to install the RMISecurityManager as the system security manager for your app. It is an example security manager that works with the default system policy and imposes some basic restrictions on what downloaded classes can do. To install the RMISecurityManager, simply add the following line to the beginning of the main( )

Screenshot-3. RMI apps and dynamic class loading
Java ScreenShot

method of both the client and server apps (yes, we'll be sending code both ways in the next section):

 main( ) {
 System.setSecurityManager( new RMISecurityManager( ) );
 ...


The RMISecurityManager works with the system security policy file to enforce restrictions. You have to provide a policy file that allows the client and server to do basic operations like make network connections. Unfortunately, allowing all the operations needed to load classes dynamically requires listing a lot of permission information and we don't want to get into that here. We suggest that for this example you simply grant the code all permissions. Here is an example policy filecall it mysecurity.policy:

 grant {
 permission java.security.AllPermission ;
 };


(It's exceedingly lame, not to mention risky, to install a security manager and then tell it to enforce no real security, but we're more interested in looking at the networking code at the moment.) To run our MyServer app, we would use a command such as:

 % java -Djava.rmi.server.codebase='http://myserver/foo/' \
 -Djava.security.policy=mysecurity.policy MyServer


Finally, one last magical incantation is required to enable dynamic class loading. As of the current implementation, the rmiregistry must be run without the classes that are to be loaded being in its classpath. If the classes are in the classpath of rmiregistry, it does not annotate the serialized objects with the URLs of their class files, and no classes are dynamically loaded. This limitation is really annoying; all we can say is to heed the warning for now. If you follow these directions, you should be able to run our client with only the MyClient class and the ServerRemote remote interface in its classpath. All the other classes are loaded dynamically from the specified server as needed.

Passing remote object references

So far, we haven't done anything that we couldn't have done with the simple object protocol. We used only one remote object, MyServer, and we got its reference from the RMI registry. Now we extend our example to pass some remote references between the client and server, allowing additional remote calls in both directions. We'll add two methods to our remote ServerRemote interface:

 public interface ServerRemote extends Remote {
 ...
 StringIterator getList( ) throws RemoteException;
 void asyncExecute( WorkRequest work, WorkListener
 listener )
 throws RemoteException;
 }


getList( ) retrieves a new kind of object from the server: a StringIterator. The StringIterator we've created is a simple list of strings with some methods for accessing the strings in order. We make it a remote object so that implementations of StringIterator stay on the server. Next, we spice up our work request feature by adding an asyncExecute( ) method. asyncExecute( ) lets us hand off a WorkRequest object as before, but it does the calculation on its own time. The return type for asyncExecute( ) is void because it doesn't actually return a value; we get the result later. Along with the request, our client passes a reference to a WorkListener object that is to be notified when the WorkRequest is done. We'll have our client implement WorkListener itself. Because this is to be a remote object, our interface must extend Remote and its methods must throw RemoteExceptions:

 //file: StringIterator.java
 import java.rmi.*;
 public interface StringIterator extends Remote {
 public boolean hasNext( ) throws RemoteException;
 public String next( ) throws RemoteException;
 }


Next, we provide a simple implementation of StringIterator, called MyStringIterator:

 //file: MyStringIterator.java
 import java.rmi.*;
 public class MyStringIterator
 extends java.rmi.server.UnicastRemoteObject
 implements StringIterator {
  
 String [] list;
 int index = 0;
 public MyStringIterator( String [] list )
 throws RemoteException {
 this.list = list;
 }
 public boolean hasNext( ) throws RemoteException {
 return index < list.length;
 }
 public String next( ) throws RemoteException {
 return list[index++];
 }
 }


MyStringIterator extends UnicastRemoteObject. Its methods are simple: it can give you the next string in the list, and it can tell you if there are any strings you haven't seen yet. Next, we discuss the WorkListener remote interface that defines how an object should listen for a completed WorkRequest. It has one method, workCompleted( ), which the server executing a WorkRequest calls when the job is done:

 //file: WorkListener.java
 import java.rmi.*;
 public interface WorkListener extends Remote {
 public void workCompleted(WorkRequest request, Object result )
 throws RemoteException;
 }


Let's add the new features to MyServer. We need to add implementations of the getList( ) and asyncExecute( ) methods, which we just added to the ServerRemote interface:

 public class MyServer extends java.rmi.server.UnicastRemoteObject
 implements ServerRemote {
 ...
 public StringIterator getList( ) throws RemoteException {
 return new MyStringIterator(
 new String [] { "Foo", "Bar", "Gee" } );
 }
 public void asyncExecute(
 WorkRequest request , WorkListener listener )
 throws java.rmi.RemoteException
 {
 new Thread( ) {
 public void run( ) {
 Object result = request.execute( );
 try {
 listener.workCompleted( request, result );
 } catch ( RemoteException e ) {
 System.out.println( e ); // error calling client
 }
 }}.start( );
 }
 }


getList( ) just returns a StringIterator with some stuff in it. asyncExecute( ) calls a WorkRequest's execute( ) method and notifies the listener when it's done. asyncExecute( ) runs the request in a separate thread, allowing the remote method call to return immediately. Later, when the work is done, the server uses the client's WorkListener interface to return the result. We have to modify MyClient to implement the remote WorkListener interface. This turns MyClient into a remote object, so we will have it extend UnicastRemoteObject. We also add the workCompleted( ) method the WorkListener interface requires. Finally, we want MyClient to exercise the new features. We've put all of this in a new version of the client called MyClientAsync:

 //file: MyClientAsync.java
 import java.rmi.*;
 import java.util.*;
  
 public class MyClientAsync
 extends java.rmi.server.UnicastRemoteObject implements WorkListener
 {
  
 public MyClientAsync(String host) throws RemoteException
 {
 try {
 RemoteServer server = (RemoteServer)
 Naming.lookup("rmi://"+host+"/NiftyServer");
  
 server.asyncExecute( new MyCalculation( 100 ), this );
 System.out.println("call done...");
 } catch (java.io.IOException e) {
 // I/O Error or bad URL
 } catch (NotBoundException e) {
 // NiftyServer isn't registered
 }
 }
  
 public void workCompleted( WorkRequest request, Object result )
 throws RemoteException
 {
 System.out.println("Async result: "+result );
 }
  
 public static void main(String [] args) throws RemoteException {
 new MyClientAsync( args[0] );
 }
  
 }
  


We use getList( ) to get the iterator from the server and then loop, printing the strings. We also call asyncExecute( ) to perform another calculation; this time, we square the number 100. The second argument to asyncExecute( ) is the WorkListener to notify when the data is ready; we pass a reference to ourselves (this). If you're running Java 5.0, just compile and you're ready to go. But if you need to generate the stubs, run rmic to make the stubs for all our remote objects:

 % rmic MyClient MyServer MyStringIterator


Restart the RMI registry and MyServer on your server, and run the client somewhere. You should get the following:

 Sun Mar 5 23:57:19 PDT 2006
 4
 Foo
 Bar
 Gee
 Async work result = 10000


If you are experimenting with dynamic class loading, you should be able to have the client download all the server's auxiliary classes (the stubs and the StringIterator) from a web server. And, conversely, you should be able to have MyServer fetch the Client stub and WorkRequest-related classes when it needs them. We hope that this introduction has given you a feel for the tremendous power that RMI offers through object serialization and dynamic class loading. Java is one of the first coding languages to offer this kind of powerful framework for distributed apps. Although some of the advanced features are not used widely in business apps, RMI is the underpinning for the very widely used J2EE Enterprise JavaBeans architecture and is an important technology. For more information on RMI and J2EE, see Java Enterprise in a Nutshell (Oracle).

RMI Object Activation

One of the newer features of RMI is the ability to create remote objects that are persistent. They can save their state for arbitrary periods of inactivity and be reactivated when a request from a client arrives. This is an important feature for large systems with remote objects that must remain accessible across long periods of time. RMI activation effectively allows a remote object to be storedin a database, for exampleand automatically reincarnated when it is needed. RMI activation is not particularly easy to use and would not have benefited us in any of our simple examples; we won't delve into it here. Much of the functionality of objects that can be activated can be achieved by using factories of shorter-lived objects that know how to retrieve some state from a database (or other location). The primary users of RMI activation may be systems such as Enterprise JavaBeans, which need a generalized mechanism to save remotely accessible objects and revive them at later times.

RMI and CORBA

Java supports an important alternative to RMI, called CORBA (Common Object Request Broker Architecture). We won't say much about CORBA here, but you should know that it exists. CORBA is an older distributed object standard developed by the Object Management Group (OMG), of which Oracle is one of the founding members. Its major advantage is that it works across languages: a Java program can use CORBA to talk to objects written in other languages, like C or C++. This is may be a considerable advantage if you want to build a Java frontend for an older program that you can't afford to reimplement. CORBA also provides other services similar to those in the Java Enterprise APIs. CORBA's major disadvantages are that it's complex, inelegant, and somewhat arcane. In recent years, Sun and IBM worked together to implement an OMG standard that bridges RMI and CORBA. Java RMI over IIOP uses the Internet Inter-Object Protocol to provide some RMI-to-CORBA interoperability. However, CORBA currently does not have many of the semantics necessary to support true RMI-style distributed objects, so this solution, though part of the JDK as of Version 1.3, is somewhat limited.

Java ScreenShot
Comments