{"record":{"id":"9728869e5329c4f6","repo":"TheAlgorithms/Java","slug":"key-and-value-must-not-be-null-972886","errorCode":null,"errorMessage":"Key and value must not be null","messagePattern":"Key and value must not be null","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/caches/RRCache.java","lineNumber":165,"sourceCode":"        put(key, value, defaultTTL);\n    }\n\n    /**\n     * Adds a key-value pair to the cache with a specified time-to-live (TTL).\n     *\n     * <p>If the key already exists, its value is updated and its TTL is reset. If the key\n     * does not exist and the cache is full, a random entry is evicted to make space.\n     * Expired entries are also cleaned up prior to any eviction. The eviction listener\n     * is notified when an entry gets evicted.\n     *\n     * @param key        the key to associate with the cached value; must not be {@code null}\n     * @param value      the value to be cached; must not be {@code null}\n     * @param ttlMillis  the time-to-live for this entry in milliseconds; must be >= 0\n     * @throws IllegalArgumentException if {@code key} or {@code value} is {@code null}, or if {@code ttlMillis} is negative\n     */\n    public void put(K key, V value, long ttlMillis) {\n        if (key == null || value == null) {\n            throw new IllegalArgumentException(\"Key and value must not be null\");\n        }\n        if (ttlMillis < 0) {\n            throw new IllegalArgumentException(\"TTL must be >= 0\");\n        }\n\n        lock.lock();\n        try {\n            if (cache.containsKey(key)) {\n                cache.put(key, new CacheEntry<>(value, ttlMillis));\n                return;\n            }\n\n            evictExpired();\n\n            if (cache.size() >= capacity) {\n                int idx = random.nextInt(keys.size());\n                K evictKey = keys.remove(idx);\n                CacheEntry<V> evictVal = cache.remove(evictKey);","sourceCodeStart":147,"sourceCodeEnd":183,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java#L147-L183","documentation":"RRCache.put() rejects null keys and null values with IllegalArgumentException before acquiring the lock. The cache does not support null values because null is not distinguishable from an absent entry in its internal structures, and null keys break key-tracking consistency.","triggerScenarios":"Calling cache.put(null, value), cache.put(key, null), or cache.put(null, null). Also triggered via the two-argument put(key, value) which delegates to put(key, value, defaultTTL).","commonSituations":"Caching a computation result that can be null on edge cases (e.g., a DB query with no match). Key produced by a deserializer or mapper that yields null for missing fields.","solutions":["Validate both key and value are non-null before calling put()","If null values are semantically valid, wrap them in Optional or use a sentinel object","Skip caching entirely when the value is null rather than storing it"],"exampleFix":"// before\ncache.put(userId, userProfile); // throws if userProfile is null\n\n// after\nif (userId != null && userProfile != null) {\n    cache.put(userId, userProfile);\n}","handlingStrategy":"validation","validationCode":"public void safePut(RRCache<String,String> cache, String key, String val) {\n    if (key == null || val == null) return;\n    cache.put(key, val);\n}","typeGuard":"Objects.requireNonNull(key, \"key\");\nObjects.requireNonNull(value, \"value\");\ncache.put(key, value);","tryCatchPattern":"try {\n    cache.put(key, value);\n} catch (IllegalArgumentException e) {\n    if (key == null || value == null) {\n        logger.debug(\"Skipped caching null key or value\");\n    } else throw e;\n}","preventionTips":["Validate key and value are non-null before put()","Use Objects.requireNonNull for fast-fail at call sites","Skip caching when the value is null rather than storing it"],"tags":["rr-cache","null-safety","validation"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}