Interface StatefulTask<K,V>

Type Parameters:
K - The data type of the Key in the state Map
V - The data type of the Value in the state Map

public interface StatefulTask<K,V>
An interface to provide means for saving & loading state for Runnable and Callable tasks scheduled with an IScheduledExecutorService. When task implements this interface, the Scheduled Executor will be able to handle state of the task among the replicas in an event of Migration or Node failure.

Example:

 public class CleanUpTask implements Runnable, StatefulTask<String, Integer>, HazelcastInstanceAware {

      private transient HazelcastInstance instance;

      private transient int recordsDeletedSoFar;

      public CleanUpTask(HazelcastInstance instance) {
          this.instance = instance;
      }

      public void run() {
          recordsDeletedSoFar += cleanUpInvalidRecordsAndReturnCount();
      }

      private int cleanUpInvalidRecordsAndReturnCount() {
      }

      public void save(Map<String, Integer> snapshot) {
          snapshot.put("recordsDeletedSoFar", recordsDeletedSoFar);
      }

      public void load(Map<String, Integer> snapshot) {
          if (state.containsKey("recordsDeletedSoFar")) {
              recordsDeletedSoFar = snapshot.get("recordsDeletedSoFar");
          }
      }
 }
 
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    load(Map<K,V> snapshot)
    Task callback to initialize its inner state, after a replica promotion, from the given map.
    void
    save(Map<K,V> snapshot)
    Task callback to capture its state on the provided map.
  • Method Details

    • save

      void save(Map<K,V> snapshot)
      Task callback to capture its state on the provided map. This is invoked after each invocation of Runnable.run() or Callable.call() to capture a snapshot of the state and publish to replicas. If two or more replicas of the same task run at the same time and publish their states, then only the one running on the owner member will be allowed to update the replicas.

      Note: The state of the cluster is not known or guaranteed during task's execution, thus, publication of the task's state to replicas is done on best-effort basis.

      Called immediately after run() or call() of the Runnable or Callable respectively.

      Parameters:
      snapshot - The Map responsible for holding a snapshot of the current state.
    • load

      void load(Map<K,V> snapshot)
      Task callback to initialize its inner state, after a replica promotion, from the given map. This is invoked once per task's lifecycle in a single member, before invocation of Runnable.run() or Callable.call() to set up task's state as published from the previous owner of the task in the cluster.

      load will not be called if the snapshot is empty.

      Parameters:
      snapshot - The Map responsible for providing a snapshot of the task's state.