Class ConnectionHealthMonitor

java.lang.Object
com.loomcache.server.network.ConnectionHealthMonitor
All Implemented Interfaces:
AutoCloseable

public class ConnectionHealthMonitor extends Object implements AutoCloseable
Monitors health status of active connections with latency, error rate, and idle time tracking.

Provides real-time health monitoring with configurable thresholds and automatic detection of unhealthy connections. Uses a background virtual thread to periodically check connection health status and invoke callbacks for state transitions.

Features:

  • Sealed interface ConnectionHealthMonitor.HealthStatus with four permit classes: Healthy, Degraded, Unhealthy, Unknown
  • Health tracking via ConnectionHealthMonitor.ConnectionHealth records
  • Configurable thresholds: max latency (default 500ms), max error rate (default 0.1), max idle time (default 60s)
  • Health check callbacks via functional interface ConnectionHealthMonitor.HealthCheckCallback
  • Auto-close unhealthy connections after configurable grace period
  • Metrics: healthy/degraded/unhealthy counts, average latency
  • Thread-safe with ReentrantLock
  • Implements AutoCloseable for proper resource cleanup
  • Uses Java 25 features: sealed interfaces, records, pattern matching, virtual threads

Health status transitions:

  • Unknown → Healthy: latency good, error rate low, no idle issues
  • Unknown → Degraded: latency or error rate approaching limits or increased idle time
  • Unknown → Unhealthy: threshold(s) exceeded
  • Healthy → Degraded: thresholds becoming problematic
  • Healthy → Unhealthy: critical threshold(s) exceeded
  • Degraded → Healthy: recovery detected
  • Degraded → Unhealthy: worsening conditions
  • Unhealthy → auto-close after grace period
Version:
1.0
Author:
ConnectionHealthMonitor Implementation
  • Constructor Details

    • ConnectionHealthMonitor

      public ConnectionHealthMonitor()
      Creates a ConnectionHealthMonitor with default configuration.
    • ConnectionHealthMonitor

      public ConnectionHealthMonitor(Clock clock)
      Creates a ConnectionHealthMonitor with custom Clock (for testing).
      Parameters:
      clock - the Clock instance for timestamping
    • ConnectionHealthMonitor

      public ConnectionHealthMonitor(Clock clock, Consumer<String> unhealthyCloseCallback)
      Creates a ConnectionHealthMonitor with a custom Clock and close callback.
      Parameters:
      clock - the Clock instance for timestamping
      unhealthyCloseCallback - invoked before an expired unhealthy connection is evicted
  • Method Details

    • startMonitoring

      public void startMonitoring()
      Starts the background health monitoring using a scheduled virtual thread. Safe to call multiple times; subsequent calls are no-ops if already running.
    • stopMonitoring

      public void stopMonitoring()
      Stops the background health monitoring.
    • registerConnection

      public void registerConnection(String connectionId)
      Registers a connection for health monitoring.
      Parameters:
      connectionId - unique identifier for the connection
      Throws:
      NullPointerException - if connectionId is null
    • unregisterConnection

      public void unregisterConnection(String connectionId)
      Unregisters a connection from health monitoring.
      Parameters:
      connectionId - the connection to unregister
    • recordSuccess

      public void recordSuccess(String connectionId, long latencyMs)
      Reports a successful activity on a connection. Resets error count and updates activity timestamp.
      Parameters:
      connectionId - the connection identifier
      latencyMs - latency of the operation in milliseconds
      Throws:
      NullPointerException - if connectionId is null
    • recordFailure

      public void recordFailure(String connectionId)
      Reports a failed activity on a connection. Increments error rate and updates activity timestamp.
      Parameters:
      connectionId - the connection identifier
      Throws:
      NullPointerException - if connectionId is null
    • performHealthCheck

      public void performHealthCheck()
      Performs a single health check cycle on all registered connections. Evaluates health status based on configured thresholds and invokes callbacks.
    • getConnectionHealth

      public @Nullable ConnectionHealthMonitor.ConnectionHealth getConnectionHealth(String connectionId)
      Gets the health information for a specific connection.
      Parameters:
      connectionId - the connection identifier
      Returns:
      ConnectionHealth record, or null if not registered
    • getMetrics

      Gets comprehensive metrics for all monitored connections.
      Returns:
      HealthMetrics containing aggregated statistics
    • addCallback

      public void addCallback(ConnectionHealthMonitor.HealthCheckCallback callback)
      Registers a callback to be invoked on health status changes.
      Parameters:
      callback - the callback to register
      Throws:
      NullPointerException - if callback is null
    • removeCallback

      public void removeCallback(ConnectionHealthMonitor.HealthCheckCallback callback)
      Removes a previously registered callback.
      Parameters:
      callback - the callback to remove
    • setMaxLatency

      public void setMaxLatency(long latencyMs)
      Sets the maximum acceptable latency threshold.
      Parameters:
      latencyMs - latency in milliseconds
      Throws:
      IllegalArgumentException - if latencyMs is non-positive
    • setMaxErrorRate

      public void setMaxErrorRate(double errorRate)
      Sets the maximum acceptable error rate.
      Parameters:
      errorRate - error rate between 0.0 and 1.0
      Throws:
      IllegalArgumentException - if errorRate is outside valid range
    • setMaxIdleTime

      public void setMaxIdleTime(long idleTimeMs)
      Sets the maximum idle time before connection is considered unhealthy.
      Parameters:
      idleTimeMs - idle time in milliseconds
      Throws:
      IllegalArgumentException - if idleTimeMs is non-positive
    • setUnhealthyGracePeriod

      public void setUnhealthyGracePeriod(long gracePeriodMs)
      Sets the grace period for auto-closing unhealthy connections.
      Parameters:
      gracePeriodMs - grace period in milliseconds
      Throws:
      IllegalArgumentException - if gracePeriodMs is non-positive
    • setHealthCheckInterval

      public void setHealthCheckInterval(long intervalMs)
      Sets the interval between health check cycles.
      Parameters:
      intervalMs - interval in milliseconds
      Throws:
      IllegalArgumentException - if intervalMs is non-positive
    • getConnectionCount

      public int getConnectionCount()
      Gets the current number of monitored connections.
      Returns:
      number of connections
    • getTotalCheckCount

      public long getTotalCheckCount()
      Gets the total number of health checks performed.
      Returns:
      total check count
    • close

      public void close()
      Closes the monitor, stopping the background monitoring thread and clearing all state.
      Specified by:
      close in interface AutoCloseable
    • reset

      public void reset()
      Resets all connection states and metrics.