Creating a timeout for Java RMI client is important since LocateRegistry.getRegistry would make your application unresponsive when the Java RMI server is not available. To create a timeout at the client-side, I suggest you to use ExecutorService. The following codes is an example how to use it:
Suppose you have your localhost listening on port 1099 for RMI and your server serve an interface
public interface RMIService() {
public String sayHello throws RemoteException;
}
Then at your client app, you do this
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
String host = "localhost";
int port = 1099;
RMIService service = (RMIService) LocateRegistry
.getRegistry(host, port).lookup("RMIService");
System.err.println(service.sayHello());
return null;
}
});
try {
future.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException |
ExecutionException e) {
System.err.println(e.getMessage());
}
The above code will try executing the remote method and will throw exception if the lookup time exceeds 5 seconds.
Hope this helps. :)