Class ConnectionHealthMonitor
java.lang.Object
com.loomcache.server.network.ConnectionHealthMonitor
- All Implemented Interfaces:
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.HealthStatuswith four permit classes: Healthy, Degraded, Unhealthy, Unknown - Health tracking via
ConnectionHealthMonitor.ConnectionHealthrecords - 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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordImmutable record containing health information for a single connection.static final classDegraded status: connection showing concerning metrics but still operational.static interfaceFunctional interface for health check callbacks.static final recordRecord containing comprehensive metrics for all monitored connections.static interfaceSealed interface representing the health status of a connection.static final classHealthy status: connection operating normally.static final classUnhealthy status: connection exceeds critical thresholds and may be closed.static final classUnknown status: no health data collected yet. -
Constructor Summary
ConstructorsConstructorDescriptionCreates a ConnectionHealthMonitor with default configuration.ConnectionHealthMonitor(Clock clock) Creates a ConnectionHealthMonitor with custom Clock (for testing).ConnectionHealthMonitor(Clock clock, Consumer<String> unhealthyCloseCallback) Creates a ConnectionHealthMonitor with a custom Clock and close callback. -
Method Summary
Modifier and TypeMethodDescriptionvoidRegisters a callback to be invoked on health status changes.voidclose()Closes the monitor, stopping the background monitoring thread and clearing all state.intGets the current number of monitored connections.@Nullable ConnectionHealthMonitor.ConnectionHealthgetConnectionHealth(String connectionId) Gets the health information for a specific connection.Gets comprehensive metrics for all monitored connections.longGets the total number of health checks performed.voidPerforms a single health check cycle on all registered connections.voidrecordFailure(String connectionId) Reports a failed activity on a connection.voidrecordSuccess(String connectionId, long latencyMs) Reports a successful activity on a connection.voidregisterConnection(String connectionId) Registers a connection for health monitoring.voidRemoves a previously registered callback.voidreset()Resets all connection states and metrics.voidsetHealthCheckInterval(long intervalMs) Sets the interval between health check cycles.voidsetMaxErrorRate(double errorRate) Sets the maximum acceptable error rate.voidsetMaxIdleTime(long idleTimeMs) Sets the maximum idle time before connection is considered unhealthy.voidsetMaxLatency(long latencyMs) Sets the maximum acceptable latency threshold.voidsetUnhealthyGracePeriod(long gracePeriodMs) Sets the grace period for auto-closing unhealthy connections.voidStarts the background health monitoring using a scheduled virtual thread.voidStops the background health monitoring.voidunregisterConnection(String connectionId) Unregisters a connection from health monitoring.
-
Constructor Details
-
ConnectionHealthMonitor
public ConnectionHealthMonitor()Creates a ConnectionHealthMonitor with default configuration. -
ConnectionHealthMonitor
Creates a ConnectionHealthMonitor with custom Clock (for testing).- Parameters:
clock- the Clock instance for timestamping
-
ConnectionHealthMonitor
-
-
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
Registers a connection for health monitoring.- Parameters:
connectionId- unique identifier for the connection- Throws:
NullPointerException- if connectionId is null
-
unregisterConnection
Unregisters a connection from health monitoring.- Parameters:
connectionId- the connection to unregister
-
recordSuccess
Reports a successful activity on a connection. Resets error count and updates activity timestamp.- Parameters:
connectionId- the connection identifierlatencyMs- latency of the operation in milliseconds- Throws:
NullPointerException- if connectionId is null
-
recordFailure
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
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
Registers a callback to be invoked on health status changes.- Parameters:
callback- the callback to register- Throws:
NullPointerException- if callback is null
-
removeCallback
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:
closein interfaceAutoCloseable
-
reset
public void reset()Resets all connection states and metrics.
-