Search code examples
javarmi

Understanding java RMI exportObject method


I'm very new to RMI and I just decided to give it a try. I got confused by the exportObject(Object, int) method. The documentation says:

Exports the remote object to make it available to receive incoming calls, using the particular supplied port. The object is exported with a server socket created using the RMISocketFactory class.

Consider the following simple example:

public interface Client extends Remote {
    void clientMethod() throws RemoteException;
}

public class ClientImpl implements Client {
    public clientMethod() throws RemoteException {
        System.out.println("clientMethod invoked");
    }
}

Client stub = (Client) UnicastRemoteObject
               .exportObject(new ClientImpl(), 56789); //<------ HERE

So we create a stub and will transfer it to another VM either manually or through RmiRegistry, doesn't matter here.

I'm confused by "[...] the object is exported with a server socket [...]"

What do they mean by that?


Solution

    • A ServerSocket is created to listen for incoming connections at the port you specified when exporting. This port can be shared between multiple remote objects.
    • The statement about the RMISocketFactory is incorrect. Where did you read that? This class has been obsolete since 1998.
    • The stub contains the server's hostname or IP address and port number, and some internal data to identify the remote object it belongs to.
    • TCP connections between the stub and the remote object are created on demand when you call remote methods, via a connection pool.

    So, when we transfer the stub to another VM (VM 0), the stub will hold a socket connection to the VM (VM 2) it was originally created on.

    No, see above.

    The VM 2 in turn will maintain a server socket to accept incoming method invocations.

    Correct.