The RMI (Remote Method Invocation) Registry is a component of Java RMI technology used for storing and locating remote objects. The RMI Registry functions as a naming service, enabling clients to look up remote object references by name and facilitating communication and data exchange across different JVMs (Java Virtual Machines).
The primary function of the RMI Registry is to provide a central directory listing all available remote objects. Each remote object is registered with a unique name in the RMI Registry. Clients query this registry using the remote object's name to obtain the corresponding reference, allowing method invocation on the remote object.
Example:
Suppose there is a remote object implementing a calculation service, such as 'CalculatorService', which provides methods for addition, subtraction, multiplication, and division. First, we create this remote object on the server side and bind it to the RMI Registry, for example, using the name 'CalcService'.
Server-side code example:
javaimport java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class CalculatorServer extends UnicastRemoteObject implements CalculatorService { protected CalculatorServer() throws RemoteException { super(); } public int add(int a, int b) throws RemoteException { return a + b; } // Other method implementations public static void main(String[] args) { try { CalculatorService calc = new CalculatorServer(); Naming.rebind("CalcService", calc); System.out.println("Calculator Service is bound and ready for use."); } catch (Exception e) { System.err.println("Calculator Server exception: " + e.toString()); e.printStackTrace(); } } }
Client-side code example:
javaimport java.rmi.Naming; public class CalculatorClient { public static void main(String[] args) { try { String url = "rmi://server.com/CalcService"; CalculatorService calc = (CalculatorService) Naming.lookup(url); int result = calc.add(5, 3); System.out.println("Result from remote calculator: " + result); } catch (Exception e) { System.err.println("Calculator Client exception: " + e.toString()); e.printStackTrace(); } } }
In this example, the client looks up the remote object named 'CalcService' via the RMI Registry and invokes its add method. Due to the RMI Registry's role, clients can easily locate and utilize the remote services provided.