I've been working on an internal Java RMI tutorial exercise, after looking at the Sun RMI tutorial, and I only kind of understand what's going on. There are a few things that seem strange to me and I'd like to know what's really going on before I give feedback on the tutorial.
The tutorial has me write the following components:
- An interface, say RemoteInterface, with the methods that we want remote access to.
- A class, say RemoteServer, implementing RemoteInterface, that, in its constructor:
- Creates a Registry object by calling
LocateRegistry.createRegistry(PORTNO) - Creates a stub RemoteInterface object by calling
UnicastRemoteObject.exportObject(this, PORTNO)and casting the result. - Binds the stub to the registry with
registry.rebind(BINDNAME, stub)
- Creates a Registry object by calling
- A class, say ServerDemo, that has a main method that just creates an instance of RemoteServer.
- A client class that calls the server using BINDNAME, and it all works fine.
First, I noticed that:
- The server carries on running after the main method is done. I have to terminate it explicitly. To my eyes, it should just create an object and then finish, but the program doesn't terminate and the client can still connect.
- If I call
registry.unbind(BINDNAME)in the RemoteServer constructor, the client stops working but the server still doesn't terminate. - If I call
UnicastRemoteObject.unexportObject(this, true);in the RemoteServer constructor, the server terminates immediately.
I'd like to know why this is happening - although if it wasn't, the server would be useless as it would just immediately terminate. (In my feedback I'm going to suggest giving RemoteServer bind and unbind methods for ServerDemo to call, rather than doing all the binding in the constructor, never unbinding, and relying on the server carrying on running for some reason - but first I'd like to understand why it happens.)
Second, I noticed that I can call UnicastRemoteObject.exportObject(this, PORTNO) before calling LocateRegistry.createRegistry(PORTNO) and everything still works. I assumed the registry would have to be set up before we could export to it, but clearly it doesn't work the way I thought.
I'd like a little info on how exportObject actually works. (I guess this ties in with the previous point - why does having an object exprted stop the program from ending?)
Also, if I export and bind a stub in one method, ready to unexport and unbind it in another method, I'd like to know whether I need to explicitly keep a reference to the stub in between. (Only the BINDNAME is necessary to unbind.) One of my colleagues reported GC issues, and while I've not noticed any myself, I can't rule them out because I don't really get what's going on.