Class ExpirationScheduler

java.lang.Object
com.loomcache.server.lease.ExpirationScheduler

public class ExpirationScheduler extends Object
Efficient expiration scheduler using a DelayQueue for event timing.

This scheduler manages pending expiration tasks and efficiently processes them when their expiration time is reached. It uses a virtual thread for background processing to avoid blocking the main application.

Features:

  • DelayQueue for O(log n) insertion and efficient timeout handling
  • Batch processing: collects multiple expired tasks before invoking callbacks
  • Virtual thread for non-blocking background work
  • Cancellation of pending expirations (with O(n) lookup)
  • Thread-safe: all operations use thread-safe collections
Since:
1.5
  • Constructor Details

    • ExpirationScheduler

      public ExpirationScheduler(Consumer<ExpirationTask> onExpiration)
      Creates a new ExpirationScheduler.
      Parameters:
      onExpiration - callback invoked for each expired task
      Throws:
      NullPointerException - if onExpiration is null
  • Method Details

    • addExpiration

      public void addExpiration(ExpirationTask task)
      Schedules a task for expiration.

      The task will be processed when its expiration time is reached. If a task for the same (dsName, key) already exists, it is replaced.

      Parameters:
      task - the expiration task to schedule (not null)
    • cancelExpiration

      public boolean cancelExpiration(String dsName, String key)
      Cancels a pending expiration for a specific key.

      If no pending expiration exists for this key, this is a no-op. Cancellation is O(n) in the queue size.

      Parameters:
      dsName - the data structure name
      key - the cache key
      Returns:
      true if a task was cancelled, false if no such task existed
    • start

      public void start()
      Starts the background processor thread.

      Creates a virtual thread that continuously processes expired tasks. Safe to call multiple times (subsequent calls are no-ops if already running).

    • shutdown

      public void shutdown()
      Stops the background processor thread.

      Waits up to 5 seconds for the processor to terminate. Safe to call even if not running.

    • getTotalScheduled

      public long getTotalScheduled()
      Gets the total number of expirations scheduled.
      Returns:
      number of addExpiration calls made
    • getTotalExpired

      public long getTotalExpired()
      Gets the total number of expirations processed.
      Returns:
      number of tasks processed so far
    • getPendingCount

      public int getPendingCount()
      Gets the number of pending expirations.
      Returns:
      size of the pending queue
    • isRunning

      public boolean isRunning()
      Gets whether the scheduler is running.
      Returns:
      true if background processing is active