In the calculator application the client executes calc.add(7, 5). Trace what happens, layer by layer, until 7 + 5 = 12 is printed.
Java RMI (Remote Method Invocation) lets a program call methods on an object in another JVM as if it were local. It is Java's object-oriented form of RPC, built from stubs, a name registry on port 1099, serialization and distributed garbage collection.
java.rmi.*) lets one JVM invoke methods on a remote object in another JVM — Java's object-oriented, Java-only version of RPC.java.rmi.Remote; every method declares throws RemoteException (checked). The implementation usually extends UnicastRemoteObject, whose constructor throws RemoteException too.rmiregistry, default port 1099. Naming.bind/rebind/unbind/lookup/list take URLs like rmi://host:1099/Name; LocateRegistry.createRegistry/getRegistry return a Registry.bind throws AlreadyBoundException if the name exists; rebind replaces it; lookup of a missing name throws NotBoundException. Only programs on the registry's own host may bind.dirty() on receiving a stub, clean() when it is dropped. Default lease 10 min (java.rmi.dgc.leaseValue = 600000 ms), renewed at half-time.rmic); rmic was removed in JDK 15 and RMI Activation in JDK 17. RMI-IIOP bridged RMI to CORBA until Java 11.In an ordinary Java program, calc.add(7, 5) jumps to code in the same process: the arguments sit on the same stack and the answer comes back in nanoseconds. In a distributed system the object you need may live in another process, usually on another machine — the head-office server rather than the district-office PC. A remote call must carry the request across the network, run it there and bring the result back, and it can fail in ways a local call never does.
Remote Procedure Call (RPC), described by Andrew Birrell and Bruce Nelson of Xerox PARC in 1984, made such calls look like ordinary function calls. A generated client stub packs the arguments into a message (marshalling); on the server a server stub unpacks them (unmarshalling), calls the real procedure and sends the result back the same way. Sun's ONC RPC, the basis of NFS, is the classic implementation: the interface is written in an IDL and compiled by rpcgen, data travels in XDR format, and a portmapper (rpcbind) on port 111 tells clients where each program listens.
Java RMI (Remote Method Invocation), added in JDK 1.1 (1997) as the java.rmi packages, is the object-oriented, Java-only form of the same idea. Instead of calling a procedure on a host, the client calls a method on a remote object living in another Java Virtual Machine (JVM). Arguments may be whole objects, and if the receiver lacks an argument's class, RMI can even download its bytecode.
java.rmi.Remote and lists the methods clients may call remotely.rpcgenThe RMI system sits between the client program and the remote object as three layers. Each layer talks only to the layers directly above and below it, so one can be replaced — a different transport, say — without changing the others.
| Layer | Client side | Server side | Job |
|---|---|---|---|
| Stub / skeleton layer | Stub — a proxy implementing the remote interface | Skeleton in JDK 1.1; since Java 2 a generic dispatcher inside the RMI runtime | Turns a method call into a request message and the reply back into a return value; marshals and unmarshals |
| Remote Reference Layer (RRL) | The remote reference (RemoteRef) held inside the stub | The server-side reference of the exported object | Defines invocation semantics — unicast point-to-point (UnicastRemoteObject), activatable objects, and so on |
| Transport layer | Opens or reuses a TCP connection to the server's endpoint | Listens for calls, keeps a table of exported objects and finds the target | Connection set-up and management; carries JRMP (Java Remote Method Protocol) |
On the server the transport receives the request, and the RRL passes it to a dispatcher that unmarshals the arguments, calls the real method on the implementation object, and marshals the result or exception back. In JDK 1.1 this dispatcher was a generated class called the skeleton (CalculatorImpl_Skel). Java 2 (JDK 1.2) introduced a new stub protocol in which the RMI runtime dispatches calls itself using reflection, so skeletons are no longer needed.
| Java version | What changed |
|---|---|
| JDK 1.1 (1997) | RMI introduced; the rmic compiler generates both Impl_Stub and Impl_Skel classes |
| J2SE 1.2 (1998) | 1.2 stub protocol — skeletons no longer required (rmic -v1.2 generates stubs only) |
| J2SE 1.3 (2000) | RMI-IIOP integrated, letting RMI objects talk to CORBA over IIOP |
| J2SE 5.0 (2004) | Stubs generated at run time as dynamic proxies, so running rmic becomes unnecessary |
| Java SE 8 (2014) | Statically generated stubs deprecated |
| Java SE 11 (2018) | CORBA and RMI-IIOP removed from the JDK |
| Java SE 15 and 17 | rmic removed (15); RMI Activation and rmid removed (17). Core RMI and rmiregistry remain |
RMI's native wire protocol is JRMP (Java Remote Method Protocol) over TCP. RMI-IIOP used CORBA's IIOP instead, so Java objects could interoperate with CORBA programs written in other languages; it carried remote EJB calls in Java EE until it was removed in Java 11.
A client needs a first reference to a remote object before it can call anything — the bootstrap problem. The RMI registry solves it: a small name server that maps simple string names to stubs. The server binds a name and the client looks it up. The registry is itself a remote object listening on a well-known port: 1099 by default.
$ rmiregistry # Linux/macOS: run in its own terminal (or "rmiregistry &"); port 1099
$ rmiregistry 2001 # listen on another port instead
C:\> start rmiregistry # Windows: opens the registry in a new windowTwo APIs reach a registry. The java.rmi.Naming class has static methods that take a URL-style name, rmi://host:port/name; the host defaults to the local machine and the port to 1099. The java.rmi.registry package gives finer control: LocateRegistry creates or locates a registry and returns a Registry object whose methods take plain names.
| Operation | Naming (static, URL names) | Registry (instance, plain names) | Notes |
|---|---|---|---|
| Bind a new name | Naming.bind("rmi://host/Calc", obj) | reg.bind("Calc", obj) | Throws AlreadyBoundException if the name is taken |
| Bind or replace | Naming.rebind(url, obj) | reg.rebind(name, obj) | Silently replaces an existing binding — the usual choice in servers |
| Remove | Naming.unbind(url) | reg.unbind(name) | Throws NotBoundException if the name is absent |
| Find | Naming.lookup(url) | reg.lookup(name) | Returns a Remote (the stub) to be cast to the remote interface; NotBoundException if absent |
| List | Naming.list(url) | reg.list() | Returns the bound names as a String[] (Naming gives them as URLs) |
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RegistryDemo {
// Server side: start a registry inside this JVM instead of running rmiregistry
static Registry startRegistry() throws Exception {
Registry reg = LocateRegistry.createRegistry(1099); // Registry.REGISTRY_PORT is 1099
reg.rebind("CalcService", new CalculatorImpl()); // plain name, not a URL
return reg; // keep this reference alive
}
// Client side: reach a registry on another host and look the name up
static Calculator find(String host) throws Exception {
Registry reg = LocateRegistry.getRegistry(host, 1099); // only builds a stub: no network call yet
return (Calculator) reg.lookup("CalcService"); // the first real remote call
}
}bind, rebind and unbind only from programs on its own host; a remote caller gets java.rmi.AccessException, although lookup and list work from anywhere. The registry must also be able to load the remote interface's class — start rmiregistry from the folder that holds the .class files, or set CLASSPATH. And LocateRegistry.getRegistry() succeeds even when no registry is running: the error appears only at the first lookup.Registry names are flat strings, not a hierarchy, and bindings survive until they are replaced or removed — even if the server that made them has died. Large systems therefore often reach RMI objects through JNDI or a directory service, but for exams the registry, port 1099 and the five operations above are what matter.
Here is a complete small application: an EMI calculator that runs on a head-office server and is called from district-office PCs. It needs four source files — the remote interface (shared by both sides), the implementation and the server (server side), and the client.
java.rmi.Remote and declare throws RemoteException on every method.UnicastRemoteObject (which exports the object), with a constructor that declares throws RemoteException.Naming.rebind.Naming.lookup, cast the result to the interface, and call methods inside a try/catch for RemoteException.javac *.java. On JDK 1.1–1.4 you would now run rmic CalculatorImpl to generate the stub (and the skeleton); since Java 5 this step is skipped.rmiregistry (port 1099) from the folder that contains the class files.java CalculatorServer, then java CalculatorClient localhost from another terminal or machine.import java.rmi.Remote;
import java.rmi.RemoteException;
// The only type the client needs to know about.
public interface Calculator extends Remote {
int add(int a, int b) throws RemoteException;
double emi(double principal, double annualRatePercent, int months) throws RemoteException;
}import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class CalculatorImpl extends UnicastRemoteObject implements Calculator {
public CalculatorImpl() throws RemoteException {
super(); // exports the object: it now listens on an anonymous TCP port
}
@Override
public int add(int a, int b) throws RemoteException {
System.out.println("add(" + a + ", " + b + ") called"); // printed on the SERVER console
return a + b;
}
@Override
public double emi(double principal, double annualRatePercent, int months) throws RemoteException {
double r = annualRatePercent / 12 / 100; // monthly interest rate
double f = Math.pow(1 + r, months); // (1 + r) to the power n
return principal * r * f / (f - 1); // EMI = P r (1+r)^n / ((1+r)^n - 1)
}
}import java.rmi.Naming;
public class CalculatorServer {
public static void main(String[] args) {
try {
Calculator calc = new CalculatorImpl(); // create and export
Naming.rebind("rmi://localhost:1099/CalcService", calc); // the registry stores its stub
System.out.println("CalcService bound. Waiting for calls...");
// main ends here, but the JVM keeps running: RMI threads serve the exported object
} catch (Exception e) {
System.err.println("Server failed: " + e);
}
}
}import java.rmi.Naming;
import java.rmi.RemoteException;
public class CalculatorClient {
public static void main(String[] args) {
String host = (args.length > 0) ? args[0] : "localhost";
try {
// lookup returns the stub; cast it to the INTERFACE, never to CalculatorImpl
Calculator calc = (Calculator) Naming.lookup("rmi://" + host + ":1099/CalcService");
System.out.println("7 + 5 = " + calc.add(7, 5));
System.out.printf("EMI = Rs %.2f per month%n", calc.emi(1000000, 9.0, 240));
} catch (RemoteException e) {
System.err.println("Network or server problem: " + e);
} catch (Exception e) { // NotBoundException, MalformedURLException
System.err.println("Lookup failed: " + e);
}
}
}$ javac *.java # compile the four source files
$ rmiregistry & # registry on port 1099 (Windows: start rmiregistry)
$ java CalculatorServer & # the server stays running in the background
CalcService bound. Waiting for calls...
$ java CalculatorClient localhost
add(7, 5) called # <- printed by the server process
7 + 5 = 12
EMI = Rs 8997.26 per monthIf the implementation must extend some other class, drop extends UnicastRemoteObject and export the object explicitly with UnicastRemoteObject.exportObject(obj, 0), which returns its stub (port 0 means "any free port"). Either way the object is now exported: it has an object ID and an endpoint where the RMI runtime accepts calls.
| Symptom | Likely cause | Fix |
|---|---|---|
java.rmi.ConnectException: Connection refused to host | Nothing is listening at that host and port — the registry or server is not running | Start rmiregistry and the server first; check the host name, port and firewall |
java.rmi.NotBoundException: CalcService | The name was never bound, or is spelt differently | Use exactly the same name string in rebind and lookup |
ServerException → UnmarshalException → ClassNotFoundException: Calculator on rebind | The registry cannot load the remote interface class | Start rmiregistry in the class folder, or set CLASSPATH |
ExportException: Port already in use: 1099 | A registry is already running and the program calls createRegistry(1099) again | Use the running registry (getRegistry) or pick another port |
MarshalException caused by NotSerializableException | An argument is neither Serializable nor a remote object (a bad return value reaches the client as UnmarshalException instead) | Implement java.io.Serializable, or make the class remote |
Two JVMs share no memory, so an argument cannot be passed as a plain pointer. Marshalling is the stub writing the method's identity and the arguments into a byte stream; unmarshalling is the receiver rebuilding live values from those bytes. Results and exceptions make the same trip in reverse. RMI marshals with Java object serialization (ObjectOutputStream / ObjectInputStream), which can flatten an entire graph of objects.
| What is passed | How RMI passes it | Effect |
|---|---|---|
Primitive (int, double, boolean …) | By value | Copied, exactly as in a local call |
Serializable object (implements java.io.Serializable): String, ArrayList, a data class | By value — the object graph is serialized and a new copy is built at the receiver | Changes the server makes affect only its copy; the caller's object is untouched |
| Remote object (exported, implements a remote interface) | By reference — its stub is sent instead of the object | Calls made on the received stub travel back to the original object (a callback) |
Neither Serializable nor remote (a Thread, a socket, an ordinary class) | Cannot be marshalled | Run-time MarshalException wrapping NotSerializableException |
Serialization copies non-static fields recursively. Fields marked transient are skipped and arrive with default values (0, false, null), and static fields are never sent. Within a single call shared references survive: if two arguments point to the same object, the server also sees one object, not two copies. A serializable class should declare a serialVersionUID, so both JVMs agree that they hold the same version of the class.
Dynamic class loading. Objects are sent with their class names, so a receiver may get an object whose class it has never seen — say a subclass HousingLoan where the interface only promises a Loan. RMI can then download the bytecode from a URL set in the sender's java.rmi.server.codebase property, which makes polymorphism work across JVMs. Since Java 7 update 21 this is off by default (java.rmi.server.useCodebaseOnly=true) for security, so most applications simply put the shared classes on both sides.
| Exception | Meaning |
|---|---|
RemoteException (checked, a subclass of IOException) | Superclass of all communication failures; every remote method must declare it |
ConnectException | No connection could be opened — nothing listening at that host and port |
MarshalException / UnmarshalException | Writing or reading the call or its result failed (non-serializable argument, missing class) |
NoSuchObjectException | The remote object no longer exists in the server JVM (it was unexported or collected) |
ServerException | A RemoteException occurred while the server processed the call; the original is nested inside |
NotBoundException / AlreadyBoundException | Registry name missing on lookup or unbind / already taken on bind |
Application exception thrown by the remote method itself (e.g. IllegalArgumentException) | Serialized and rethrown at the client unchanged, so the client catches it as usual |
synchronized methods or other locking, exactly like any multithreaded server.Inside one JVM the garbage collector frees an object once nothing refers to it. With RMI a client JVM may hold a stub for a server object, and the server's collector cannot see references stored in another machine's memory. RMI therefore adds a distributed garbage collector (DGC): it keeps a remote object alive while any client holds a live reference, and lets it be collected afterwards.
dirty() on the server's DGC. The server adds that client to the object's reference set and grants a lease.java.rmi.dgc.leaseValue milliseconds — 600,000 ms (10 minutes) by default. The client renews it with further dirty() calls, normally when half the lease has elapsed.clean(), and the client leaves the reference set.java.rmi.server.Unreferenced is told first through unreferenced().Because the DGC is a form of reference counting, it cannot reclaim distributed cycles: two remote objects in different JVMs that hold stubs to each other keep each other alive. Leases also mean a crashed client can pin an object for up to one lease period. A client that calls an object already unexported or collected gets NoSuchObjectException.
All four technologies hide the network behind a call, but they differ in what they pass, who can take part and how they cross firewalls. Exam questions often ask which one is language-neutral, which one uses XML, or which registry and port belong to which.
| Feature | RPC (Sun ONC) | Java RMI | CORBA | Web services (SOAP) |
|---|---|---|---|---|
| Style | Procedural — call a function | Object-oriented — call a method | Object-oriented — call a method | Service-oriented — send a message to an operation |
| Languages | Mainly C; language-specific bindings | Java only, on both ends | Language-neutral (C, C++, Java, Python … through IDL mappings) | Any language and platform |
| Interface definition | RPC language (.x file) compiled by rpcgen | Java interface extending Remote | OMG IDL | WSDL (XML) |
| Data format | XDR (binary) | Java serialization (binary) | CDR (binary) | XML (text) |
| Wire protocol | ONC RPC over UDP or TCP | JRMP over TCP (or RMI-IIOP) | GIOP / IIOP over TCP | SOAP over HTTP (also SMTP, JMS …) |
| Naming / discovery | Portmapper (rpcbind), port 111 | RMI registry, port 1099 | Naming Service, Trading Service | UDDI registry |
| Objects as parameters | No — data only | Copies (Serializable) or references (Remote) | Object references; valuetypes by value | No — XML documents only |
| Distributed GC | None | Yes — leases | None (explicit life cycle) | None (usually stateless) |
| Firewalls | Poor (dynamic ports) | Poor (dynamic ports) | Poor | Good — ports 80/443 |
| Origin | Sun, 1980s (RFC 1057, 1988) | Sun, JDK 1.1 (1997) | OMG, CORBA 1.0 (1991) | W3C: SOAP 1.1 (2000), 1.2 (2003) |
Where RMI stands today. RMI is still part of Java SE (java.rmi) and is used inside Java-only systems — the JMX remote-management connector is one example — but new cross-language services normally use web services (SOAP or REST) or gRPC. Remote EJBs relied on RMI-IIOP until its removal in Java 11, and RMI Activation (rmid) went in Java 17.
Try the problem first, then reveal the working one step at a time.
In the calculator application the client executes calc.add(7, 5). Trace what happens, layer by layer, until 7 + 5 = 12 is printed.
Applicant is a Serializable class with fields name and status (initially "PENDING"). The remote method approve(Applicant a) sets a.status = "APPROVED" and returns a.name + " " + a.status. The client runs Applicant x = new Applicant("Asha");, then prints stub.approve(x), then prints x.status. What is printed? What changes if (a) Applicant is not Serializable, or (b) Applicant is a remote interface implemented by an exported object in the client JVM, and the server calls a.setStatus("APPROVED") on it?
A server exports LoanServiceImpl with java.rmi.dgc.leaseValue=360000 and binds it in an rmiregistry running in another JVM at t = 0 min. Client A looks it up at t = 1, and its stub is garbage-collected at t = 4. Client B looks it up at t = 2 and crashes at t = 7. The server unbinds the name at t = 9. Clients renew at half the lease, and every clean() is sent the moment a stub is dropped. When does the object's reference set become empty?
For each case choose RPC, RMI, CORBA or a SOAP web service and justify: (a) a Java admin console on the office LAN calling a Java allotment server and passing Applicant objects; (b) a bank's .NET system calling the housing board's Java loan service across the Internet, through firewalls; (c) a legacy C program on a Unix server exposing a few procedures to other C programs, NFS-style; (d) an older system whose C++ and Java components share remote objects through an interface language.
Write the remote interface and implementation class for a BalanceService that returns the outstanding loan balance for an account number, and a server that binds it under the name BalanceService in a registry on port 2001.
A remote method is int addTask(ArrayList<String> list) throws RemoteException { list.add("Inspect site"); return list.size(); }. The client runs ArrayList<String> tasks = new ArrayList<>(); tasks.add("Survey"); tasks.add("Estimate"); int n = stub.addTask(tasks); System.out.println(n + " " + tasks.size());. What is printed, and why?
Judge each item on its own, assuming the rest of the program is correct. Is it fine, a compile-time error or a run-time error, and how would you fix it? (1) public interface Hello extends Remote { String hi(); } (2) public class HelloImpl extends UnicastRemoteObject implements Hello { public String hi() { return "hi"; } } with no constructor written; (3) in the client, HelloImpl h = (HelloImpl) Naming.lookup("rmi://localhost/Hello"); (4) in the client, Naming.lookup is called inside a main that has no throws clause and no try/catch.
A server is started with -Djava.rmi.dgc.leaseValue=240000. (a) How long is the lease, and about how often does a client renew it? (b) A client crashes. What are the shortest and longest times after the crash for which its lease can keep the remote object alive?
A server calls Naming.bind("rmi://localhost/Calc", obj). It runs fine, is stopped with Ctrl+C and started again while the same rmiregistry keeps running. What happens at the second start, and how do you fix it? What does a client that looked up Calc before the restart see when it calls a method on its old stub?
rmic producing both _Stub and _Skel classes.UnicastRemoteObject() throws it), and the client must catch or declare it. Leaving it off an interface method compiles but fails when the object is exported.Naming vs Registry names: Naming.lookup takes a URL such as rmi://host:1099/Calc, while Registry.lookup takes just Calc. LocateRegistry.getRegistry() makes no network call, so it "succeeds" even when no registry is running.rmid; 111 is the ONC RPC portmapper.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.