Skip to content

Add remove, computeIfAbsent and keys() - #1

Merged
kasapdev merged 1 commit into
mainfrom
feat/remove-compute-keys
Sep 20, 2026
Merged

kasapdev merged 1 commit into
mainfrom
feat/remove-compute-keys

Conversation

@kasapdev

Copy link
Copy Markdown
Owner

What

Adds three methods to LruCache:

  • V remove(K key) removes an entry and returns its live value (null if absent/expired).
  • V computeIfAbsent(K key, Function loader) (plus an overload with an explicit ttlMillis) returns the cached value or computes, stores and returns it.
  • List<K> keys() returns a snapshot of the live keys, least- to most-recently-used (eviction order).

Why

The cache offered no way to invalidate a single key, so callers had to clear() everything or wait for TTL. The "get, check for null, load, put" pattern was left to every caller, and done naively from several threads it loads the same value repeatedly (a thundering herd on a cold key). computeIfAbsent runs under the existing lock, so concurrent callers for one key trigger exactly one load. keys() gives a debugging/inspection view without perturbing recency.

Behaviour

  • remove is not a lookup: hit/miss statistics are untouched.
  • computeIfAbsent counts as exactly one hit or one miss. A null loader result stores nothing; a thrown exception propagates and stores nothing; an expired entry is treated as a miss. Documented caveat: the loader runs under the lock, so it must not call back into the cache.
  • keys() does not refresh recency (it iterates the entry set, which is not an access in access-ordered LinkedHashMap) and skips expired entries.
  • Additive: no change to existing methods. CHANGELOG.md (1.3.0) and the README API table are updated.

Testing

Compiled with javac -Xlint:all (no warnings) and LruCacheTest passes, with 23 new checks covering: remove return values, expired/absent, size and freed-slot reuse, and no stat impact; computeIfAbsent hit/miss accounting, null result, exception, both TTL overloads, and null-loader rejection; a contention test where 8 threads race for one key and the loader runs exactly once; and keys() ordering, being a detached copy, not changing which entry gets evicted, and skipping expired entries.

🤖 Generated with Claude Code

@kasapdev
kasapdev merged commit 69b8bea into main Sep 20, 2026
2 checks passed
@kasapdev
kasapdev deleted the feat/remove-compute-keys branch September 20, 2026 00:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant