Class AsyncButOrdered<K>

  • Type Parameters:
    K - the type of the key

    public class AsyncButOrdered<K>
    extends Object
    Helper class to perform an operation asynchronous but keeping the order in respect to a given key.

    A typical use pattern for this helper class consists of callbacks for an abstract entity where the order of callbacks matters, which eventually call user code in form of listeners. Since the order the callbacks matters, you need to use synchronous connection listeners. But if those listeners would invoke the user provided listeners, and if those user provided listeners would take a long time to complete, or even worse, block, then Smack's total progress is stalled, since synchronous connection listeners are invoked from the main event loop.

    It is common for those situations that the order of callbacks is not globally important, but only important in respect to an particular entity. Take chat state notifications (CSN) for example: Assume there are two contacts which send you CSNs. If a contact sends you first 'active' and then 'inactive, it is crucial that first the listener is called with 'active' and afterwards with 'inactive'. But if there is another contact is sending 'composing' followed by 'paused', then it is also important that the listeners are invoked in the correct order, but the order in which the listeners for those two contacts are invoked does not matter.

    Using this helper class, one would call performAsyncButOrdered(Object, Runnable) which the remote contacts JID as first argument and a Runnable invoking the user listeners as second. This class guarantees that runnables of subsequent invocations are always executed after the runnables of previous invocations using the same key.