How to Accurately Count Valid Entries in Redisson RMapCache

This article explains why Redisson's RMapCache.size() includes expired entries, demonstrates how to obtain the exact number of currently valid key‑value pairs using keySet().size() or readAllEntrySet().size(), and provides performance tips and a real‑world e‑commerce use case.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
How to Accurately Count Valid Entries in Redisson RMapCache

Introduction: Why We Need This Feature

In distributed systems, caching is a key performance component. Redisson, a Java client for Redis, offers the RMapCache data structure with expiration support, but developers often need to know the amount of currently valid (non‑expired) cached data.

Monitor cache hit rate

Optimize cache strategy

Trigger business logic when data expires

Ensure cache freshness

The method RMapCache.size() returns the total number of key‑value pairs, including expired ones, which does not meet these needs.

Core Issue: Why size() Falls Short

Redis uses lazy deletion plus periodic eviction, so expired keys may remain until accessed or cleaned up. Consequently, size() reports the total key count, not the count of currently valid keys.

RMapCache<String, User> userCache = redissonClient.getMapCache("userCache");
int totalSize = userCache.size(); // Wrong! Includes expired keys

The size() method returns the total number of entries in the map, ignoring expiration status.

Key difference: size() → total entries stored in Redis keySet().size() → count of currently valid (non‑expired) entries

Correct Solution: Getting the Count of Non‑Expired Entries

Redisson automatically filters expired keys when accessing them, so the following approaches return the correct valid count.

Method 1: Use keySet().size()

long validCount = userCache.keySet().size();

The keySet() call filters out expired keys by checking TTL, ensuring the returned set contains only currently valid keys.

Method 2: Use readAllEntrySet().size()

Set<Map.Entry<String, User>> entries = userCache.readAllEntrySet();
long validCount = entries.size();

This approach retrieves both keys and values, useful when you need to iterate over valid entries.

Method 3: Asynchronous Non‑Blocking Retrieval (High Concurrency)

RFuture<Set<String>> future = userCache.keySetAsync();
future.whenComplete((keys, exception) -> {
    if (exception == null) {
        long validCount = keys.size();
        // Business logic, e.g., trigger cache‑monitoring alerts
    }
});

Suitable for web services to avoid blocking the main thread and improve response time.

Why These Methods Work

When keySet() or readAllEntrySet() is called, Redisson fetches the current keys from Redis, which automatically excludes expired keys, so the collection size reflects the truly valid entries.

Business Case: Inventory Cache Monitoring in an E‑Commerce Platform

Background

An e‑commerce platform caches product inventory using RMapCache with a 30‑second TTL per item.

MapCache<String, Integer> stockCache = redissonClient.getMapCache("stockCache");
stockCache.put("product_1001", 100, 30, TimeUnit.SECONDS);

Problem

Inventory cache must be updated in real time.

Low valid cache count can cause a surge of database traffic.

Need to monitor cache health and trigger pre‑warming.

Solution

public class StockCacheMonitor {
    private final RMapCache<String, Integer> stockCache;
    private final int threshold = 50; // valid cache threshold

    public StockCacheMonitor(RMapCache<String, Integer> stockCache) {
        this.stockCache = stockCache;
    }

    public void monitorCacheValidity() {
        int validStockCount = stockCache.keySet().size();
        if (validStockCount < threshold) {
            log.warn("Warning: valid stock cache count low, current: {}", validStockCount);
            // Add cache pre‑warming logic here
        }
    }
}

Business Value

Prevent database pressure: Pre‑warm cache before the valid count drops below the threshold.

Accurate monitoring: Real‑time insight into cache validity, avoiding reliance on the inaccurate size() method.

Data freshness guarantee: Users see up‑to‑date inventory information.

Performance Considerations and Best Practices

1. Performance Optimization for Large Data Sets

When RMapCache holds many entries, keySet() loads all keys into memory, which can affect performance.

// Not recommended for large data sets
int validCount = redissonClient.getMapCache("largeCache").keySet().size();

// Recommended: paginate traversal
int count = 0;
Iterator<String> iterator = redissonClient.getMapCache("largeCache").keySet().iterator();
while (iterator.hasNext()) {
    iterator.next();
    count++;
}

2. Asynchronous Retrieval (Avoid Blocking Main Thread)

RFuture<Set<String>> futureKeys = redissonClient.getMapCache("userCache").keySetAsync();
futureKeys.whenComplete((keys, exception) -> {
    if (exception == null) {
        int validCount = keys.size();
        log.info("Valid cache count: {}", validCount);
    } else {
        log.error("Failed to get cache count", exception);
    }
});

3. Reasonable Monitoring Frequency

Avoid real‑time polling (multiple times per second).

Recommend collecting statistics every 30 seconds to 1 minute.

Adjust frequency based on business scenarios.

Common Questions and Solutions

Q: Why does the obtained non‑expired count sometimes appear lower than expected?

A: Redis deletes expired keys lazily; some keys may have expired but not yet been removed. keySet() automatically filters these, returning the truly valid count.

Q: How to avoid performance issues caused by frequent retrieval?

Reduce monitoring frequency (e.g., every 30 seconds).

Use paginated traversal instead of loading all keys at once.

Apply only in critical business scenarios such as inventory monitoring.

Q: Performance comparison with size() ?

size() – fast but includes expired keys, low accuracy. keySet().size() – moderate speed, high accuracy, suitable when exact valid count is required. readAllEntrySet().size() – slower due to fetching values, but provides both keys and values.

Conclusion: Precise Retrieval of Non‑Expired Data Is Key to Cache Management

In Redisson's RMapCache, avoid using size(). Instead, use keySet().size() or readAllEntrySet().size() to obtain the count of valid entries, ensuring accurate cache health monitoring and optimal performance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaRedisredissonCache MonitoringkeySetRMapCache
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.