How can an object in one JVM call a method on an object in a different JVM (different machine)? Normal method calls only work within the same JVM. We need a mechanism that makes remote calls feel like local calls.
RMI is a Java mechanism that allows an object in one JVM to invoke methods on an object located in another JVM. It creates the illusion of local method calls by handling all network communication transparently through stubs and serialization.
- Remote Interface defines methods that can be called remotely (extends Remote)
- Implementation class implements the interface (extends UnicastRemoteObject)
- Server registers the object with RMI Registry using Naming.rebind()
- Client looks up the object using Naming.lookup() and gets a stub
- Client calls method on stub
- Stub serializes parameters, sends request over network
- Server receives, deserializes, executes method
- Result is serialized and sent back
- Client deserializes and returns result
- Location transparency: Client cannot tell if object is local or remote
- Object serialization: Parameters/returns converted to byte streams
- Stub/Skeleton: Client proxy and server proxy handle communication
- RMI Registry: Naming service to locate remote objects
- Garbage collection: Remote objects can be collected when no references exist
- Security: Can use SecurityManager to control remote code execution
- Built from: Object Serialization — serializes data for network transfer
- Builds into: EJB Object — EJB uses RMI underneath
- Builds into: RMI Registry — provides naming for RMI objects
- Related: JNDI — JNDI is a generalized naming system beyond RMI
- Contrasts with: Socket Programming — RMI is higher level
- Network failures can cause RemoteException
- Serialization has performance cost
- Pass-by-value for normal objects, pass-by-reference for Remote objects
- Class must be available on both client and server
- Not used much today — replaced by REST, gRPC, SOAP