After initial bootstrapping an RMI client receives a stub to the server. Now I'm able to either keep this reference and use it throughout the client or I can do a lookup in the registry every time. I am not sure what is the best approach.
As far as I currently know the reference to the stub may become invalid if the servers decides to garbage collect the remote object or if the server is restarted. For this reason I tend not to keep the reference but to lookup the stub every time through the registry. On the other hand this may have a performance penalty.
Is someone willing to advice me on the subject? Thanks in advance.
Mike Peters wrote:I don't know how to handle that in an elegant way (i.e. the mechanism will pollute the client code). What is your solution?
May be you can spend some time looking into creating a decorator over the actual stub that does a reconnect when it gets a remote exception. Something like:
All your client code interacts with the above decorator and not the actual stub. So, none of them actually has to care about stub refresh.
You can even look at dynamic proxies if you have a lot of such stubs and you do not want to write a new decorator for every server stub that you have.
Nitesh Kant wrote:May be you can spend some time looking into creating a decorator over the actual stub that does a reconnect when it gets a remote exception.
Nitesh thanks, the decorator looks like a good pattern if the "other pattern" of "caching" the stub reference is the preferred approach. But I can save myself the hassle of caching the stub reference if the overhead of retrieving a stub from the registry is minimal. I hope someone has an advice about why one approach is better than the other. So currently I see three methods for handling RMI stubs:
Always retrieve a stub from the registry. (easy to code and safe but maybe slow) <- is it really slow?
Get a stub from the registry once and use that throughout a whole session. (easy to code, fast but maybe leads to unexpected RemoteExceptions) <- is it really error prone?
Cache a stub from the registry for reuse and if the stub fails retry an operation with a new stub from the registry and replace the cached stub with that new one. (probably fast, safe but harder to code) <- is it really fast?
Well, frankly slow and fast are very relative terms. What may be slow for one application may be acceptable for another.
The best way to make a decision on what you want to do is to try it out, measure the latency in your environment and then make a decision.
Having said that, theoretically if the latency of a network call in your environment is X then taking the 1st approach you have mentioned, the latency is always 2X.
On the other hand, in other approaches it is X in best case and 2X in worst i.e when you refresh the stub. So, theoretically, I will choose the stub cache and refresh approach. YMMV