Search code examples
javaconcurrencyrmiheartbeat

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


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?


Solution

  • You can implement user-mode threading in a non-threaded environment by liberally scattering a self-written "yield" function in your code.

    Similarly, you could liberally scatter heartbeat check function calls in your code. Forgo the thread, simply regularly call a heartbeat function which checks to see if a heartbeat yet needs to be sent.

    It's a crude solution, but given you've tried the proper solution and it doesn't work, perhaps it's something you have to fall back to.

    In fact what you could do is place a macro at the beginning of every function call, which does a quick check on the time and calls the heartbeat function when necessary.

    (Ah, do you have macros in Java? I think not - but you get the idea).