For cometd client wait for publish message in queue before shutting down

217 Views Asked by At

We are shutting down cometd client in the below fashion. Is there a way we can ensure that all the pending events are published ? Sometimes we are seeing issue where some of the events send just before triggering shutdown is lost.

public void shutdown() {

        try {
            if (bayeuxClient != null) {
                bayeuxClient.getChannel(getChannelInfo()).unsubscribe();
                bayeuxClient.disconnect(10000L);
                bayeuxClient.waitFor(10000L, BayeuxClient.State.DISCONNECTED);
            }
            if (client != null) {
                client.stop();
            }
        } catch (Exception e) {
            log.warn(e.getMessage());
        } finally {
            client = null;
            bayeuxClient = null;
        }

    }
1

There are 1 best solutions below

0
sbordet On

If you are publishing and disconnecting from concurrent threads, there is a possibility that the disconnect overtakes the publish.

In general, this issue must be resolved at the application level, i.e. it is the application that should coordinate the last publish and the disconnect.

You have the following choices:

Use Batching

Batching ensures ordering:

bayeuxClient.batch(() -> {
  // Last publish
  bayeuxClient.getChannel("/foo").publish("data");
  bayeuxClient.disconnect();
  // You can wait here.
  bayeuxClient.waitFor(10000L, BayeuxClient.State.DISCONNECTED);
});

Use MessageListener

Use a message listener from the publish() so that you are notified of when the last publish is complete, and then you can disconnect:

// Last publish
bayeuxClient.getChannel("/foo").publish("data", publishReply -> {
  // Do not wait inside CometD listeners.
  bayeuxClient.disconnect();
});
// Wait outside CometD listeners. 
bayeuxClient.waitFor(10000L, BayeuxClient.State.DISCONNECTED);