Class ConcurrentWeakCache<K,V>
java.lang.Object
org.eclipse.aether.util.concurrency.ConcurrentWeakCache<K,V>
- Type Parameters:
K- the type of keysV- the type of values
A concurrent cache with weak keys and weak values, inspired by maven-impl's Cache class
but stripped down and optimized for hot-path performance.
Design compared to the full Cache:
- Zero allocation on get() — uses a ThreadLocal reusable lookup key instead of allocating a new wrapper on every read
- O(1) cleanup per stale entry — uses identity-based removal from
the ReferenceQueue instead of a full
entrySet().removeIf()scan - Lock-free reads —
ConcurrentHashMap.get(Object)is a volatile read with no lock acquisition - Lock-striped writes — ConcurrentHashMap uses fine-grained locking
Keys are held via WeakReference: when a key is no longer strongly referenced
elsewhere, its entry becomes eligible for garbage collection. Values are also held
via WeakReference. Stale entries are cleaned up lazily on put(K, V).
- Since:
- 2.0.19
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a new cache with default initial capacity.ConcurrentWeakCache(int initialCapacity) Creates a new cache with the given initial capacity. -
Method Summary
Modifier and TypeMethodDescriptionReturns the value for the given key, ornullif the key is not present or the value has been garbage collected.voidStores a key-value pair in the cache.putIfAbsent(K key, V value) If the key is not already present (or its value has been GC'd), stores the key-value pair and returns the given value.intsize()Returns the number of entries in the cache (including possibly stale ones).
-
Constructor Details
-
ConcurrentWeakCache
public ConcurrentWeakCache()Creates a new cache with default initial capacity. -
ConcurrentWeakCache
Creates a new cache with the given initial capacity.- Parameters:
initialCapacity- the initial capacity
-
-
Method Details
-
get
-
put
-
putIfAbsent
If the key is not already present (or its value has been GC'd), stores the key-value pair and returns the given value. If the key is already present with a live value, returns the existing value without storing. Concurrent callers for the same key are guaranteed to receive the same instance (the insert-or-keep decision is atomic per key viaConcurrentHashMap.merge(K, V, BiFunction)).Also performs lazy cleanup of entries whose keys have been garbage collected.
- Parameters:
key- the keyvalue- the value to store if absent- Returns:
- the existing value if present, or the given value if newly stored
-
size
Returns the number of entries in the cache (including possibly stale ones).- Returns:
- the cache size
-