This topic explains how to safely modify the cache from an event handler callback in VMware Tanzu GemFire.

Event handlers are synchronous. If you need to change the cache or perform any other distributed operation from event handler callbacks, be careful to avoid activities that might block and affect your overall system performance.

Operations to Avoid in Event Handlers

Do not perform distributed operations of any kind directly from your event handler. Tanzu GemFire is a highly distributed system and many operations that may seem local invoke distributed operations.

These are common distributed operations that can get you into trouble:

  • Calling Region methods, on the event’s region or any other region.
  • Using the Tanzu GemFire DistributedLockService.
  • Modifying region attributes.
  • Executing a function through the Tanzu GemFire FunctionService.

To be on the safe side, do not make any calls to the Tanzu GemFire API directly from your event handler. Make all Tanzu GemFire API calls from within a separate thread or executor.

How to Perform Distributed Operations Based on Events

If you need to use the Tanzu GemFire API from your handlers, make your work asynchronous to the event handler. You can spawn a separate thread or use a solution like the java.util.concurrent.Executor interface.

This example shows a serial executor where the callback creates a Runnable that can be pulled off a queue and run by another object. This preserves the ordering of events.

public void afterCreate(EntryEvent event) {
  final Region otherRegion = cache.getRegion("/otherRegion");
  final Object key = event.getKey();
  final Object val = event.getNewValue();

  serialExecutor.execute(new Runnable() {
    public void run() {
      try {
        otherRegion.create(key, val);
      }
      catch (org.apache.geode.cache.RegionDestroyedException e) {
        ...
      }
      catch (org.apache.geode.cache.EntryExistsException e) {
        ...
      }
    }
  });
}

For additional information about the Executor, see the SerialExecutor example on the Oracle Java web site.

check-circle-line exclamation-circle-line close-line
Scroll to top icon