Explain Java RMI(Remote Method Invocation) Concept With Example

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using two objects stub and skeleton.

The is given the 6 steps to write the RMI program.

  1. Create the remote interface
  2. Provide the implementation of the remote interface
  3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
  4. Start the registry service by rmiregistry tool
  5. Create and start the remote application
  6. Create and start the client application

We have followed all the 6 steps to create and run the rmi application. The client application requires only two files, the remote interface and the client application. In the Rmi application, both the client and the server communicate with the remote interface. The client application uses methods in the proxy object that sends the RMI request to the remote JVM. Return will be sent to the proxy item and then to the client application.

  1. Create the remote interface

Here, we are creating a remote interface that extends the Remote interface. There is only one method named add() and it declares RemoteException.

2. Provide the implementation of the remote interface

Here, we extend the UnicastRemoteObject class, you must define a constructor that declares RemoteException.

3. Create the stub and skeleton objects using the rmic tool.

rmic AdderRemote

4. Start the registry service by the rmiregistry tool

rmiregistry 5000

5. Create and run the server application

In this example, we are binding the remote object by the name karshan.

6. Create and run the client application

In this example, we are running the server and client applications, in the same machine so we are using localhost.

For running this rmi example,

1. compile all the java files
javac *.java

2. create stub and skeleton object by rmic tool
rmic AdderRemote

3. start rmi registry in one command prompt
rmiregistry 5000

4. start the server in another command prompt
java MyServer

5. start the client application in another command prompt
java MyClient

Output of this RMI example

Thank you.

Final Year Undergraduate | Software Engineering University of Kelaniya.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store