Dont Hold Connections to a Server Youre Not Using

Consume as few server resources as possible, for as short a time as is reasonable. This rule of thumb has two main consequences: dont hold connections to a server youre not using, and validate arguments on the client-side whenever reasonable.

9.4.1 Dont Hold Connections to a Server Youre Not Using

The client has to connect to the server. Recall that, in a typical application, this is done in two steps: 1. The client connects to the naming service. 2. The client gets a connection to the server it wants by making a call to the naming service. When using the RMI registry, this is often accomplished in a single line of code. For example, our bank client connects to a particular account in the following line of code: _account = AccountNaming.lookup_accountNameField.getText ; The essence of this rule of thumb is this: as soon as is reasonable, set the stub variable to null . In the account client, we actually have a pair of methods for handling our connections. One establishes the connection and one releases it. private void getAccount { try { _account = AccountNaming.lookup_accountNameField.getText ; } catch Exception e { System.out.printlnCouldnt find account. Error was \n + e; e.printStackTrace ; } return; } private void releaseAccount { _account = null; } Next, whenever we need to make a method call, we call both of these. For example, here is the code that gets the account balance all of our operations are implemented as subclasses of ActionListener : private class GetBalanceAction implements ActionListener { public void actionPerformedActionEvent event { try { getAccount ; resetBalanceField ; releaseAccount ; } catch Exception exception { System.out.printlnCouldnt talk to account. Error was \n + exception; exception.printStackTrace ; } } } This establishes a connection, makes the query, and then releases the connection. Doing this enables the RMI runtime to perform distributed garbage collection and thus allows the server to perform cleanup actions e.g., releasing resources, persisting state at fairly appropriate times. However, in order for this to work, clients have to be good distributed citizens and relinquish their connections when they are done. Its possible to take this too far. If the client is going to make more method calls on the same server in a short period of time, its perfectly reasonable to keep a reference to the stub. If the client doesnt keep a reference to the active stub, the client will just have to contact the naming service again, and re-establish the same connection to the server.

9.4.2 Validate Arguments on the Client Side Whenever Reasonable