Search code examples
publish-subscribehazelcastevent-listener

Hazelcast EntryListener, how to avoid race condition?


I'm trying to develop a subscription service using Hazelcast. The subscription would listen for entries added to a specific Map that satisfy a predicate. This can be achieved fairly easily with an EntryListener.

However the local cache of the Map is not empty when I add the EntryListener (and the Map constantly receives updates). If you add an EntryListener to a Map which contains entries the EntryListener is not fired for any preexisting entries in the Map.

I could call map.values( <predicate> ) but it is always possible for an entry to be added just after iterating through the Map but before the EntryListener is added since the call to map.values(...) and the call to map.addEntryListener(...) are not atomic.

In an ideal solution the sequence of events would be:

  1. Add EntryListener with predicate
  2. Receive all entries in the cache that match that predicate
  3. Then receive updates/removes/adds as the events occur (matching the initial predicate).

Solution

  • Although it is an enterprise feature, continuous-query-cache seems what you want. Please see pre-population part. Pre-population helps to fill your cache from underlying imap by getting a snapshot of it according to supplied predicate. You can also find some samples here.