Search code examples
javarmi

Is there an effective way to test if a RMI server is up?


I have a RMI client testing if a RMI server is running and reachable.

At the moment I perform every few seconds this test:

try {
    rMIinstance.ping();
} catch (RemoteException e) {
    getInstanceRegister().removeInstance(rMIinstance);
}

(ping() is a simple dummy RMI call.)

If the instance is offline the I get approx 1 minute later a

java.net.ConnectException: Connection timed out

exception, showing me that the server is offline.

However the code hangs one minute, which is far to long for us. (I don't want to change the timeout setting.) Is there a method to perform this test faster?


Solution

  • You could interrupt the thread from a timer. It's a bit hacky and will throw InterruptedException instead of RemoteException, but it should work.

    try {
        Timer timer = new Timer(true);
        TimerTask interruptTimerTask = new InterruptTimerTask(Thread.currentThread());
        timer.schedule(interruptTimerTask, howLongDoYouWantToWait);
        rMIinstance.ping();
        timer.cancel();
    } catch (RemoteException | InterruptedException e) {
        getInstanceRegister().removeInstance(rMIinstance);
    }
    

    And the TimerTask implementation:

    private static class InterruptTimerTask extends TimerTask {
        private Thread thread;
    
        public InterruptTimerTask(Thread thread) {
            this.thread=thread;
        }
    
        @Override
        public void run() {
            thread.interrupt();
        }
    
    }