This advantage is that the details of socket communication and marshalling data is hidden from the programmer.
RMI is supported by three packages: java.rmi, java.rmi.server, java.rmi.activation (new in Java 1.2), and java.rmi.registry. Use of RMI requires a program to generated Java programs, rmic, and a server to broker communication, registry. Both programs are part of the standard JDK1.2 distribution.
A simple example.
Begin by defining an interface, say, Identifiable.java which extends extends Java class java.rmi.Remote (Java API documentation) (local copy). This interface accounces the procedure calls to be provided to remote clients.
Implement the interface, by writing, say, IdentityRemoteObject.java which extends Java class java.rmi.server.UnicastRemoteObject (Java API documentation) (local copy)
javac Identifiable.java IdentityRemoteObject.java
rmic IdentityRemoteObjectyielding
IdentityRemoteObject_Stub.class IdentityRemoteObject_Skel.class
(The source, _Stub.java and _Skel.java is created. Take a look at it for informational purposes.)
IdentityRemoteObject_Stub.java IdentityRemoteObject_Skel.java
javac IndentifyServer.java
# start registry > rmiregistry [9901] & [N] pid1
rmiregistry (sun copy) (local copy)
# start java IdentityServer localhost 9901 > java IdentityServer localhost 9901 & [M] pid2
Naming.lookup ("//host:9901/identity")This returns (a handle to) the remote object
Identifiable o = (Identifiable) Naming.lookup ("//host:9901/identity")
> java IdentityClient localhost ryan maelstrom.cs.fit.edu Thu Apr 29 12:40:04 EDT 1999
> kill %N %M
Another example -- a feeble authenticating server.
Other examples from Java by Example.
It is possible for a remote object to be notified when all clients disconnect by implementing the java.rmi.server.Unreferenced interface (in addition of the others)