Operating System Concepts with Java – Chapter 4.6.3

Java Remote Method Invocation (RMI)

RMI is a java feature similar to Remote Procedure Call.

There are two fundamental differences:-

RPCs support procedural programming where procedures or functions may be called whereas RMI supports invocation of methods on remote objects.

 

Parameters to RPC procedures are plain data, but with RMI it is possible to pass objects as parameters (using object serialization) to remote methods. Object serialization allows the state of an object to be written to a byte stream.

 

Building Distributed Applications

An interface must be declared that specifies the methods that can be invoked remotely. This interface must extend the java.rmi.Remote interface. Each method declared in this interface must throw Remote exceptions.

 

Example:-

// This is the interface definition

import java.rmi.*;

import java.util.Date;

 

public interface RemoteDate extends Remote

{

   public abstract Date getDate() throws RemoteException;

}

 

// This is the server

import java.rmi.*;

import java.rmi.server.UnicastRemoteObject;

import java.util.Date;

 

public class RemoteDateImpl extends UnicastRemoteObject implements RemoteDate

{

   public RemoteDateImpl()throws RemoteException {}

 

   public Date getDate() throws RemoteException {

      return new Date();

   }

 

   public static void main(String[] args) {

      try {

         RemoteDate dateServer = new RemoteDateImpl();

         Naming.rebind(“DateServer”, dateServer);

      }

      catch (Exception e) {

         System.err.println(e);

      }

   }

}
// This is the RMI client

import java.rmi.*;

 

public class RMIClient

{

   public static void main (String args[]) {

      try {

        // 127.0.0.1 is IP address of local host

        String host =

“rmi://127.0.0.1/DateServer”;

 

        // lookup the rmiregistry

        RemoteDate dateServer =

            (RemoteDate)Naming.lookup(host);

                

        System.out.println(dateServer.getDate());

      }

      catch (Exception e) {

         System.err.println(e);

      }

   }

}

 

NB: Remote methods and Naming.lookup can throw exceptions.

 

Running distributed programs

 

1. Compile all source files

 

2. Generate the stub and skeleton by entering

     rmic RemoteDateImpl

 

A stub is a proxy for a remote method, it resides with the client. When a client invokes a remote method, the stub for the remote method is called which parcels the method name and parameters. These are passed to the server where the skeleton for the remote object unmarshalls the parameters and invokes the desired method.

 

3. Start the registry

  rmiregistry &

 

4. Create the remote object

   java RemoteDateImpl

This remote object will register using the name DateServer.

 

4. Reference the remote object form a client program

   java RMIClient