Java Remote Method Invocation (RMI) gives clients access to objects in the server virtual machine (VM) in one of two ways: by reference or by value. To access a remote object by reference, the object must be an instance of a class that:
- Implements an interface that extends
java.rmi.Remote
- Has a properly generated RMI stub class that implements the same interface
- Is properly exported to allow incoming RMI calls
The interface implemented both by that class and its stub is referred to as the object's remote interface, and the methods declared in that interface can be invoked remotely. Clients only need to know about the remote interface. When they request a reference to a remote object that implements that interface, RMI substitutes an instance of the stub class and returns a copy of that stub to the client. Method calls on the RMI stub are forwarded to the remote object, which is still in the server VM. The substitution of a stub for the remote object happens automatically -- you just need to ensure that the server object implements the remote interface and is properly exported.
With pass-by-reference, all methods on the object are remote calls. That lets the remote object have access to the server's resources and services and, because multiple clients can talk to the same object on the server, changes made to that object's state by one client are visible to all clients. However, all the problems of network communications -- latency, disconnects, and time-outs, for example -- still apply.
Clients access an object by value when a remote call results in a return value of an object that implements java.io.Serializable
instead of java.rmi.Remote
. In that case, the returned object is serialized, sent to the client's VM, and deserialized, instantiating a copy of the object in the client's VM. Methods invoked on this copy are just like any other Java method -- they execute locally, without communicating with the server.
For pass-by-value, none of the network communication problems occur; however, the copy does not have easy access to server-side resources and services. Further, each time a client makes the remote method call to get the object, a new copy is created in the client VM. Since each copy maintains its own state, the changes made in one object cannot be seen by any other object.
Situations may arise that require a blend of those two strategies: an object in which some methods execute locally, without network latencies and other problems, and some methods that execute on the server. Ideally, some parts of the object's state could be shared, so that all clients could see changes, and other parts of the state kept private. In the CORBA world, that problem is solved with a construct called a smart proxy.
Smart proxies
A smart proxy is a class, instantiated in the client VM, that holds onto a remote object reference. It implements the object's remote interface and typically forwards most of the calls on the interface to the remote object, just like an RMI stub. However, a smart proxy is more useful than the RMI stub in that you can change the behavior of the remote interface to do more than forward calls to the remote object. For instance, a smart proxy can locally cache state from the remote object to avoid the network overhead on every method call.
CORBA implementations typically use a client-side object factory to instantiate smart proxies. The application calls a method of the factory to request a remote object reference. The factory gets the remote object reference, instantiates a smart proxy object that implements the same interface, and stores the remote reference in the proxy. The proxy is then returned to the caller.
That approach works in pure Java applications as well. It has a few drawbacks, however. Client-side code typically has to know about the implementation of the server's objects, for instance, in order to know which attributes are safe to cache and which need to be read from the server each time. Another problem is that, as the server application changes, some remote objects that were good candidates for smart proxies might no longer be appropriate; other classes that didn't need a smart proxy on the client might now need one. Each of those changes requires changes on the client code that may already be distributed.
A better solution would be to take advantage of RMI's ability to dynamically download classes that the client doesn't know about at runtime and implement the use of smart proxies in the server's code. That way, the client only knows that it is getting an object that implements the remote interface -- it doesn't know whether the object is a remote reference, a copy of a remote object, or a smart proxy. The server developer can, in fact, change the implementation from one of those to the other, and the client will continue to work without change.
To implement smart proxies in the server, it helps to understand how RMI passes object references:
- If the object returned from a remote method call implements an interface that extends
java.rmi.Remote
, the JVM believes that object should be a remote object and tries to construct an instance of the RMI stub for it. The stub is returned in place of the original object's reference. That is the pass-by-reference case as explained above; calls on the stub are forwarded to the server object. - Otherwise, if the object implements
java.io.Serializable
, the object itself is serialized and sent to the client VM, which then creates a copy of the object. (Primitive types, such asbyte
,char
,boolean
,int
, andfloat
, are always serialized and passed by value.) That is the pass-by-value case. - Finally, if neither of the above cases hold, an exception is thrown.
When a serializable object is sent to the client VM, each of the object's non-transient fields goes through the same scrutiny. That is, if the field's type is a class that implements an interface that extends java.rmi.Remote
(and it's not declared transient
), an RMI stub is generated, sent to the client, and substituted for the field in the client's copy of the remote object. If the field is a reference to a serializable object, a copy of the field's data is serialized and sent to the client. In that case, the field in the client's VM will refer to that deserialized copy. That occurs recursively until all of the object graph's nontransient fields have been examined and sent appropriately.
A smart proxy must, therefore, implement java.io.Serializable
, while not implementing an interface that extends java.rmi.Remote
. At the same time, the proxy must implement the same interface as the server object. That allows the client to use the proxy as if it was the server object. Achieving all three of those goals might appear a little tricky, however. How does the proxy implement the server object's interface and not implement java.rmi.Remote
? The answer lies in refactoring the way remote objects are typically implemented.
Conventional remote objects
"Beg your pardon, sir, but your excuse, 'We've always done it this way,' is the most damaging phrase in the language."
-Rear Admiral Grace Hopper, Ret.
Suppose that you want remote access to a Door
object that contains methods, which return the door location and detect if the door is open. To implement that in Java RMI, you need to define an interface that extends java.rmi.Remote
. That interface would also declare the methods that comprise the object's remote interface. Likewise, you need to define a class that implements that interface and can be exported as a remote object. The easiest way to define that class is to extend java.rmi.server.UnicastRemoteObject
. That leads to the design shown in the UML class diagram below.
The remote interface, Door
, extends java.rmi.Remote
and declares the interface you need for Door
objects. DoorImpl
is the class that actually implements the Door
interface. DoorImpl
also extends java.rmi.server.UnicastRemoteObject
so that instances of it can be accessed remotely.
Below is the code that you could use to implement that design:
/** * Define the remote interface of a Door. * @author M. Jeff Wilson * @version 1.0 */ public interface Door extends java.rmi.Remote { String getLocation() throws java.rmi.RemoteException; boolean isOpen() throws java.rmi.RemoteException; } /** * Define the remote object that implements the Door interface. * @author M. Jeff Wilson * @version 1.0 */ public class DoorImpl extends java.rmi.server.UnicastRemoteObject implements Door { private final String name; private boolean open = false; public DoorImpl(String name) throws java.rmi.RemoteException { super(); this.name = name; } // in this implementation, each Door's name is the same as its // location. // we're also assuming the name will be unique. public String getLocation() { return name; } public boolean isOpen() { return open; } // assume the server side can call this method to set the // state of this door at any time void setOpen(boolean open) { this.open = open; } // convenience method for server code String getName() { return name; } // override various Object utility methods public String toString() { return "DoorImpl:["+ name +"]"; } // DoorImpls are equivalent if they are in the same location public boolean equals(Object obj) { if (obj instanceof DoorImpl) { DoorImpl other = (DoorImpl)obj; return name.equals(other.name); } return false; } public int hashCode() { return toString().hashCode(); } }
Now that you've defined and implemented the Door
interface, the next step is to allow remote clients to access Door
's various instances. One way to do that is to bind each instance of DoorImpl
to the RMI registry. The client would then have to construct a URL that contained the name of each Door
it wanted, and do a naming service lookup on each Door
to retrieve its RMI stub. That not only clutters up the RMI registry with a lot of names (one for each Door
), but it is unnecessary work for the client as well. A better approach is to have one object bound in the RMI registry that keeps a collection of all the Door
s in the server. Clients can look up the name of that object in the registry, then make remote method calls on the object to retrieve specific Door
s. The design of such a DoorServer
is shown in Figure 2. Notice that DoorServer
and DoorServerImpl
looks a lot like Door
and DoorImpl
because you are defining another remote interface (DoorServer
) and the class that implements it (DoorServerImpl
). One difference is that DoorServerImpl
hangs on to a collection of DoorImpl
. It will use that collection to fulfill its public Door.getDoor(String location)
method.
Here's one possible implementation of the DoorServer
design:
/** * We need a class to serve Door objects to clients. * First, create the server's remote interface. * @author M. Jeff Wilson * @version 1.0 */ public interface DoorServer extends java.rmi.Remote { Door getDoor(String location) throws java.rmi.RemoteException; } /** * Define the class to implement the DoorServer interface. * @author M. Jeff Wilson * @version 1.0 */ public class DoorServerImpl extends java.rmi.server.UnicastRemoteObject implements DoorServer { /** * HashMap used to store instances of DoorImpl. The map will be keyed * by each DoorImpl's name attribute, so it is implied that two Doors * with the same name are equivalent. */ private java.util.Hashtable hash = new java.util.Hashtable(); public DoorServerImpl() throws java.rmi.RemoteException { // add a door to the hashmap DoorImpl impl = new DoorImpl("location1"); hash.put(impl.getName(), impl); } /** * @param location - String value of the Door's location * @return an object that implements Door, given the location */ public Door getDoor (String location) { return (Door)hash.get(location); } /** * Bootstrap the server by creating an instance of DoorServer and * binding its name in the RMI registry. */ public static void main(String[] args) { System.setSecurityManager(new java.rmi.RMISecurityManager()); // make the remote object available to clients try { DoorServerImpl server = new DoorServerImpl(); java.rmi.Naming.rebind("rmi://host/DoorServer", server); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
Finally, to wrap things up, the client code that gets an instance of Door
might look like this:
try { // get the DoorServer from the RMI registry DoorServer server = (DoorServer)Naming.lookup("rmi://host/DoorServer"); // Use DoorServer to get a specific Door Door theDoor = server.getDoor("location1"); // invoke methods on the returned Door if (theDoor.isOpen()) { // handle the door-open case ... } } catch (Exception e) { e.printStackTrace(); }
In that implementation, the client has to find the DoorServer
by asking the RMI registry for it (via the call to Naming.lookup(URL)
). Once the DoorServer
is found, the client can ask for specific Door
instances by calling DoorServer.getDoor(String)
, passing the Door
's location.