Class Stats
- All Implemented Interfaces:
Runnable
This class collects and provides access to various server statistics including:
- Server uptime
- Total number of requests processed
- Number of active connections
- CPU usage percentage
- Memory usage in GB
The Stats class runs on a separate platform thread and uses the OSHI library to collect system-level metrics such as CPU and memory usage.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic StatsReturns the singleton instance of the Stats collector.org.json.JSONObjectRetrieves all current server statistics as a JSON object.voidIncrements the total request counter by one.static voidinit()Initializes the singleton Stats instance and starts its monitoring thread.voidrun()Main execution loop for the stats collector thread.voidsetActiveConnections(AtomicLong activeConnections) Sets the active connections counter to a new value.
-
Constructor Details
-
Stats
public Stats()
-
-
Method Details
-
init
public static void init()Initializes the singleton Stats instance and starts its monitoring thread.This method creates a new Stats instance if one doesn't exist and starts a platform thread to run the stats collector. The thread is named "Stats-Trhead" (note: typo in original code).
This method should be called once during application startup.
-
getInstance
-
getStatsAsJson
Retrieves all current server statistics as a JSON object.The returned JSON object contains the following fields:
- uptime: Server uptime in milliseconds
- totalRequests: Total number of requests processed
- activeConnections: Current number of active connections
- cpuUsage: Current CPU usage as a percentage (0.0 to 1.0)
- memoryUsage: Current memory usage in gigabytes
- Returns:
- A JSONObject containing all server statistics.
- Throws:
InterruptedException- if the CPU usage measurement is interrupted.
-
incrementRequests
public void incrementRequests()Increments the total request counter by one.This method is thread-safe and should be called whenever a new request is processed.
-
setActiveConnections
Sets the active connections counter to a new value.This method replaces the internal active connections counter with the provided value. It's typically used to synchronize the stats with an external connection tracker.
- Parameters:
activeConnections- The new AtomicLong counter for active connections.
-
run
public void run()Main execution loop for the stats collector thread.Currently, this method simply sleeps indefinitely and does not perform any periodic statistics collection. The thread will only wake up if interrupted or if the running flag is set to false.
Note: This implementation suggests that statistics are collected on-demand via
getStatsAsJson()rather than on a periodic schedule.
-