Skip to content
Tutorials Center
My learning

Topics

Lesson 144 of 201 ยท Networking

Remote Method Invocation (RMI)

Learn Java RMI - remote interfaces, exporting objects, the registry, stubs, serialized arguments, remote exceptions and callbacks - with a loopback demo you can run.

With sockets you send bytes and decide what they mean: you design a protocol, parse requests, format replies. That is flexible but tedious when what you really want is "call a method on an object that lives in another program". Remote Method Invocation (RMI) is Java's built-in answer. You define a Java interface, implement it on a server, and a client calls it like any local object. RMI turns the call into a message, sends it over TCP, runs it remotely and returns the result or the exception.

RMI is a good way to learn how distributed calls really work: serialization, stubs, naming and failure. It is also a legacy technology. New systems usually choose REST over HTTP, gRPC or message queues, mostly because those work from any language. RMI still appears in older enterprise applications and in JMX, the monitoring interface of the JVM, so understanding it is useful. Everything in this lesson runs on our server, with the "server" and the "client" in one JVM talking over the loopback network, exactly as two separate processes would.

The pieces

An RMI application has five ingredients:

Piece Role
Remote interface Extends java.rmi.Remote; every method declares throws RemoteException. It is the contract the client sees.
Implementation A normal class implementing that interface on the server.
Export Making the object callable: UnicastRemoteObject.exportObject(impl, port) opens a listener (port 0 picks a free one) and returns a stub.
Registry A tiny name service (LocateRegistry.createRegistry(port), default port 1099) that maps names like "calculator" to stubs.
Stub A client-side proxy object that implements the remote interface. Calling a method on it sends a network request.

The client never sees the implementation class. It looks up a name in the registry, gets a stub that implements Calculator, and calls methods on it. Since Java 5 the stub is a dynamic proxy generated at run time, so you no longer run a stub compiler; the old rmic tool has been removed from the JDK.

sequenceDiagram
    participant C as Client
    participant R as Registry on port 1099
    participant S as Server object
    S->>R: rebind("calculator", stub)
    C->>R: lookup("calculator")
    R-->>C: stub (serialized)
    C->>S: stub.add(2, 40) over TCP
    S-->>C: 42

The registry only hands out stubs; the actual calls go straight from the client to the exported object.

A complete loopback example

This program contains both sides. The server exports an object and registers it; the client looks it up and calls it. Look for the three rules that make RMI work: the interface extends Remote, each method throws RemoteException, and everything crossing the wire is Serializable.

Java A remote Calculator, registry and stub

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows what happens behind each line:

  • registry.list() shows the single bound name. The registry stores the stub, not your object.
  • The stub is a java.lang.reflect.Proxy, as promised. It implements the Calculator interface only, so a client cannot cast it to CalculatorImpl.
  • calc.order(...) returned a Receipt record. Its servedBy field says the work ran on an RMI worker thread, not on the thread that made the call: the server handles each request on its own thread, so server objects must be thread-safe.
  • calc.mutate(mine) changed the server's copy of the list, and the client's list is unchanged. That is the most important semantic difference from local calls: arguments and results are passed by copy (serialization), not by reference.
  • Looking up an unknown name throws NotBoundException. After unexportObject, calling the old stub fails with NoSuchObjectException, a subclass of RemoteException.

Pass by copy, and the exception to it

Normal objects are serialized: the client gets a deep copy of a returned object, and the server gets a copy of arguments. So the argument types and results must implement Serializable, and large object graphs are expensive to send. The exception is an object that implements Remote and is exported: instead of a copy, its stub is sent, and calls on it go back to the original. That is how callbacks work, as the next example shows.

Because a call crosses a network, any remote call can fail even if your code is correct: connection refused, timeout, server restarted. This is why every remote method must declare RemoteException (a checked exception). Handle it deliberately: retry idempotent calls, report errors to the user, but never swallow it silently. Also design remote interfaces to be coarse-grained: one call that returns a whole Receipt is far better than five calls fetching one field each, because each call has round-trip latency.

Exceptions and callbacks

Application exceptions declared by the remote method are serialized too and rethrown on the client, with their type intact. And since remote objects can be passed as arguments, a client can export its own object and hand the server a stub, so that the server can call the client back: a notification system without polling.

Java Remote exceptions and a client callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Follow the sequence in the output:

  • shop.buy("tea", 2) succeeded and left 0. The second buy made the server throw OutOfStockException; the client caught the very same type with the server's message.
  • The client exported a Listener and passed the resulting stub to subscribe. When restock ran on the server, it called l.restocked(...), which executed in the client's JVM (hence the "callback" line printed there). The CountDownLatch waits for that line, because the callback may finish after restock returns to us.
  • After the restock, a normal purchase worked again.

In a real application, the client and server are separate programs, so you would put the remote interface, Receipt/exception classes and any other shared types in a shared library that both depend on. The server then runs createRegistry (or an external rmiregistry tool) and rebind. The client runs only the lookup and the calls.

Java
// Typical standalone client: connect to the machine that runs the server
Registry registry = LocateRegistry.getRegistry("shop.example.com", 1099);
Shop shop = (Shop) registry.lookup("shop");
int left = shop.buy("tea", 1);

Practical issues

  • Hostname. The stub contains the server's address. If the server believes its name is localhost or an internal address, remote clients get stubs they cannot reach. Set -Djava.rmi.server.hostname=<public address> (as the examples do with 127.0.0.1).
  • Firewalls. The registry uses one port; each exported object uses another unless you pass a fixed port to exportObject(impl, port). Fix the ports in production so you can open them.
  • Keeping the server alive. An exported object keeps the JVM running because RMI runs non-daemon threads. To shut down cleanly, unexportObject everything, as the demos do; otherwise the program never exits.
  • Garbage collection. Remote references are tracked by distributed garbage collection (leases, renewed periodically). If the client dies, the server can collect the object. Keep a strong reference to an exported object on the server, or it may be unexported by GC.
  • Security. Deserialization of untrusted data is dangerous. Never expose an RMI registry to the internet, set a serialization filter (ObjectInputFilter, or sun.rmi.registry.registryFilter and sun.rmi.transport.dgcFilter for the built-in services) to allow only the classes you expect, and prefer TLS: pass SslRMIClientSocketFactory and SslRMIServerSocketFactory to exportObject. The old practice of downloading classes from a remote codebase is disabled by default and should stay that way; the Security Manager it depended on is gone.
  • What was removed. RMI Activation (starting objects on demand) and RMI-IIOP (CORBA interop) are gone from current JDKs. Plain JRMP RMI, as shown here, remains.

RMI compared with the alternatives

Approach Strengths Weaknesses
RMI Almost no code, Java types and exceptions end to end Java-only, serialization risks, awkward with firewalls
REST/JSON over HTTP Any language, easy to cache and inspect You write the client, error mapping and types
gRPC Typed contracts, streaming, many languages Needs a schema compiler and libraries
Message queues Decoupling, retries, buffering Asynchronous: no immediate answer

Choose RMI for a small, trusted, all-Java system, or when you maintain one. For anything public or polyglot, use HTTP-based services, as the Advanced Java lessons do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about a remote interface is correct?

    Remote marks the interface as callable from other JVMs, and each method declares RemoteException because any network call can fail.
  2. 2. A client passes an ArrayList to a remote method, and the server adds an element to it. What does the client see?

    Ordinary arguments are serialized and copied. Only exported remote objects are passed as stubs, which refer back to the original.
  3. 3. What does the RMI registry store?

    The registry is a simple name service. It stores stubs under names so clients can find them, but it does not run or proxy the calls.
  4. 4. How can a server call back a client?

    Remote objects are passed as stubs. The server calls methods on the client's stub, which run in the client's JVM.
  5. 5. Why must server-side remote objects be thread-safe?

    The RMI runtime dispatches incoming calls on worker threads, so two clients can be inside the same remote object at once.

Summary

  • RMI lets a client call methods of an object in another JVM through a stub; you write a Remote interface, an implementation, export it and bind it in a registry.
  • Every remote method declares RemoteException; plan for network failures and keep calls coarse-grained.
  • Arguments and results are serialized copies unless they are exported remote objects, which travel as stubs; that is also how client callbacks work.
  • Server objects handle concurrent calls on worker threads and must be thread-safe.
  • Set the server hostname, fix ports behind firewalls, unexport objects to let the JVM exit, and apply serialization filters and TLS. Never expose the registry publicly.
  • Prefer HTTP-based services or gRPC for new, public or polyglot systems; RMI fits small trusted Java-only systems and legacy code.

Next: Java GUI Overview, the start of the desktop programming chapter, where you will meet AWT, Swing and JavaFX.