Class CacheStats


  • public class CacheStats
    extends Object
    Statistics for cache performance monitoring and analysis.

    This class provides comprehensive metrics about cache usage, including hit/miss rates, eviction counts, load times, and other performance indicators. All statistics are thread-safe and updated atomically during cache operations.

    Basic Usage Examples:

    
     // Enable statistics when creating cache
     CacheConfig<String, String> config = CacheConfig.<String, String>builder()
             .maximumSize(1000L)
             .recordStats(true) // Enable statistics collection
             .build();
     Cache<String, String> cache = new DefaultCache<>(config);
    
     // Perform some operations
     cache.put("key1", "value1");
     cache.get("key1"); // Hit
     cache.get("key2"); // Miss
    
     // Analyze performance
     CacheStats stats = cache.stats();
     System.out.println("Hit rate: " + (stats.hitRate() * 100) + "%");
     System.out.println("Total requests: " + (stats.hitCount() + stats.missCount()));
     

    Performance Monitoring Examples:

    
     // Periodic monitoring
     ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     scheduler.scheduleAtFixedRate(() -> {
         CacheStats stats = cache.stats();
    
         // Log key metrics
         logger.info("Cache Performance Report:");
         logger.info("  Hit Rate: {:.2f}%", stats.hitRate() * 100);
         logger.info("  Miss Rate: {:.2f}%", stats.missRate() * 100);
         logger.info("  Evictions: {}", stats.evictionCount());
         logger.info("  Average Load Time: {:.2f}ms", stats.averageLoadTime() / 1_000_000.0);
    
         // Alert on poor performance
         if (stats.hitRate() < 0.8) {
             logger.warn("Low cache hit rate: {:.2f}%", stats.hitRate() * 100);
         }
     }, 0, 5, TimeUnit.MINUTES);
    
     // Reset statistics for a fresh measurement period
     stats.reset();
     

    Metrics Description:

    • Hit Count: Number of successful cache lookups
    • Miss Count: Number of cache lookups that didn't find a value
    • Hit Rate: Ratio of hits to total requests (hits + misses)
    • Miss Rate: Ratio of misses to total requests (hits + misses)
    • Eviction Count: Number of entries removed due to size/weight limits
    • Load Count: Number of times the cache loader was invoked
    • Load Failure Count: Number of failed load operations
    • Average Load Time: Average time in nanoseconds for load operations
    Since:
    1.0.0
    See Also:
    Cache.stats(), CacheConfig.Builder.recordStats(boolean)
    • Method Detail

      • getEvictionCount

        public AtomicLong getEvictionCount()
      • getLoadFailureCount

        public AtomicLong getLoadFailureCount()
      • getTotalLoadTime

        public AtomicLong getTotalLoadTime()
      • hitCount

        public long hitCount()
        Returns the number of successful cache lookups.

        A hit occurs when a requested key is found in the cache and the cached value is not expired.

        Returns:
        the total number of cache hits
      • missCount

        public long missCount()
        Returns the number of cache lookups that didn't find a cached value.

        A miss occurs when a requested key is not found in the cache or the cached value has expired.

        Returns:
        the total number of cache misses
      • evictionCount

        public long evictionCount()
        Returns the number of entries that have been evicted from the cache.

        Evictions occur when the cache needs to remove entries to stay within configured size or weight limits.

        Returns:
        the total number of evicted entries
      • loadCount

        public long loadCount()
        Returns the number of times the cache loader was invoked.

        This includes both successful and failed load attempts.

        Returns:
        the total number of load operations
      • loadFailureCount

        public long loadFailureCount()
        Returns the number of failed cache load operations.

        A load failure occurs when the cache loader throws an exception or returns null for a requested key.

        Returns:
        the total number of failed load operations
      • totalLoadTime

        public long totalLoadTime()
        Returns the total time spent loading values, in nanoseconds.

        This represents the cumulative time spent in all cache loader invocations. Use averageLoadTime() for the average load time per operation.

        Returns:
        the total load time in nanoseconds
      • hitRate

        public double hitRate()
        Returns the ratio of successful cache lookups to total requests.

        The hit rate is calculated as: hits / (hits + misses). A higher hit rate indicates better cache effectiveness.

        Example:

        
         CacheStats stats = cache.stats();
         double hitRatePercent = stats.hitRate() * 100;
         System.out.printf("Cache hit rate: %.2f%%\n", hitRatePercent);
         
        Returns:
        the hit rate as a value between 0.0 and 1.0
      • missRate

        public double missRate()
        Returns the ratio of failed cache lookups to total requests.

        The miss rate is calculated as: misses / (hits + misses). This is equivalent to: 1.0 - hitRate().

        Example:

        
         CacheStats stats = cache.stats();
         double missRatePercent = stats.missRate() * 100;
         if (missRatePercent > 20.0) {
             System.out.println("High miss rate detected: " + missRatePercent + "%");
         }
         
        Returns:
        the miss rate as a value between 0.0 and 1.0
      • averageLoadTime

        public double averageLoadTime()
        Returns the average time spent loading a value, in nanoseconds.

        This is calculated as: totalLoadTime / loadCount. If no loads have occurred, returns 0.0.

        Example:

        
         CacheStats stats = cache.stats();
         double avgLoadTimeMs = stats.averageLoadTime() / 1_000_000.0;
         System.out.printf("Average load time: %.2f ms\n", avgLoadTimeMs);
         
        Returns:
        the average load time in nanoseconds
      • recordHit

        public void recordHit()
      • recordMiss

        public void recordMiss()
      • recordEviction

        public void recordEviction()
      • recordLoad

        public void recordLoad​(long loadTime)
      • recordLoadFailure

        public void recordLoadFailure()
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getHitRate

        public double getHitRate()
        Compatibility method for getHitRate() - alias for hitRate().
        Returns:
        the hit rate as a value between 0.0 and 1.0
      • getMissRate

        public double getMissRate()
        Compatibility method for getMissRate() - alias for missRate().
        Returns:
        the miss rate as a value between 0.0 and 1.0