I have my server set up with a GUI such that you can start and stop the server at will through the GUI. The server is an RMI-based server. I'm having a problem when trying to start the server after stopping it previously. I am doing the following actions:

  1. Start GUI
  2. Select "Start Server" [server starts up without issue]
  3. Select "Stop Server" [server stops without issue]
  4. Select "Start Server" - here is where the problem lies.


I am sometimes receiving an exception: "java.rmi.server.ExportException: Port already in use"

I know that you use the UnicastRemoteObject.unexportObject() call to remove the server object from the RMI registry, and this call is occurring. The problem is occurring sporadically and only happens after I've started and stopped the server at least once. If I start it and receive that error, then try to start it again, it starts without issue. Sometimes, if I start/stop then start again, it does not give me the error. It's as if the unbind() and unexportObject() calls aren't really finishing by the time I go to start the server again.

I've tried doing it so that there's a delay between the time I stop it and when I try starting it again, but it doesn't appear to affect it (at least with a 5 or 10 second wait). Is there some way of checking if the port is really in use and to bypass the error if it's not really in use? The startup code does include a second try:

Java Code:
try
{
	bindServer(); // Does the Naming.bind() call
}
catch (ServerAlreadyRunningException e) // Exception I made to detect whether the server is already running to avoid clashes between two instances on different JVM's
{
	return;
}
catch (Exception e)
{
	try
	{
		bindServer();
	}
	catch (CannotStartServerException e1)
	{
		throw e1;
	}
	catch (Exception e1)
	{
		Log.error(e1);
		return;
	}
}