What's the cleanest way to have a client terminate a RMI server that is no longer needed?

Govind Seshadri

The cleanest way to exit is to convert your remote object into an activatable remote object and then a client can invoke the Activatable.unexportObject() method to get rid of it.

Things are a little more complicated if you do not have an activatable remote object. It is very important that your server does not exit before the client's request has been fully processed, as otherwise an UnmarshallException is thrown.

One approach is to define an "exit handler thread" as an inner class, and instantiate it within the remote object's constructor. The exit handler can then loop in the background, waiting for an "exit" flag to be set by the client via an RMI call. As soon as the flag is set, the exit handler can then wait for a couple of seconds such that the client call is completely processed, and then call System.exit() to terminate the server.