How can I guarantee a "stay alive" heartbeat is sent?

Simon Nickerson picture Simon Nickerson · Mar 24, 2009 · Viewed 7.2k times · Source

We have an RMI client application written in Java which needs to send periodic "stay alive" messages to a server application. We have implemented this as a separate heartbeat thread, which sends the stay alive message to the server, then sleeps for 15 seconds using Thread.sleep().

The thread is set to be high priority:

Thread heartbeatThread = new Thread(new HeartbeatRunnable(server));
heartbeatThread.setPriority(Thread.MAX_PRIORITY);
heartbeatThread.start();

However, when the box on which the client is running is using lots of CPU, we find that heartbeats are missed, which causes the server to assume our client application has died.

We have added Thread.yield() calls in my main thread, although this has not made the problem go away.

Is there any way of guaranteeing that heartbeats are sent on time while my application is still running?

Answer

Bombe picture Bombe · Mar 24, 2009

You can not really guarantee it. You could send the heartbeat in a different thread to prevent the time it takes to send the heartbeat being added to your delay. It may also be advisable to set the delay between two heartbeats to half the time the server uses to decide a client is dead, i.e. if your server times out your client after 15 seconds, (try to) send a heartbeat every 7.5 seconds.