Roel De Nijs wrote:I kept the static reference in the class that's used to start the RMI-server.
Ok, now I figured out what I meant to ask you! But firstly, nice find
. I've not seen this mentioned in any tutorial or book that I've read on RMI. It is obviously quite important!
You have a class that you use to start the RMI-server. Do you actually create an instance of this class or it is just a utility class with static methods?
I am guessing that it is the latter. You have a static method to start the RMI-server. That is why you have to store your
RemoteBusinessLogicImpl instance as a static variable.
Another Approach
If the whole idea is to prevent the JVM from GC'ing (Garbage Collecting) your instance of
RemoteBusinessLogicImpl then there is one more logical place to put it. Place a reference to it in your server GUI as an instance variable rather than a static.
Making the a static reference to the instance of
RemoteBusinessLogicImpl is not what prevents it from being GC'd. It is keeping a reference to it that prevents the JVM from GC'ing the instance of
RemoteBusinessLogicImpl . Creating a static reference is not the key point. That reference could be a static field or an instance field. The key point is creating a reference that will exist for the lifetime of the server.
You can be guaranteed that your instance of
RemoteBusinessLogicImpl will not be GC'd if you assign it to an instance variable of your server GUI class.
An Example
So you would have...
Benefits of Other Approach
Nice separation of concerns. The
RemoteBusinessLogic lives with the server window which it relates to - logical one-to-one association here. The registry is created - no need to wrap a one liner inside a custom class. The register-method is a static method that is only concerned with registering the remote service - it makes no sense for such a class to hold a state.
Keeping your instance of
RemoteBusinessLogic alive is obviously important as you found from your
testing. So making it an instance variable of your server GUI class makes it more prominent rather than holding on to it as a side effect in a utility class.