-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Interner type for weakKey equality caching (fixes #344)
A weak keyed cache uses identity equivalence, as this is the only sensible approach when caching a value. If Objects.equals was used then the user would not be inclined to hold a reference to the canonical key and expect any equivalent key to cause the mapping to be retained. As that is an impossible expectation, the cache would seemingly discard prematurely. Therefore we disallow this case to hint that users should be more thoughtful about their desired behavior. An interner is a Set-based cache where the key is the only item of interest. This allows usages to resolve to a canonical instance, discard duplicates as determined by Object.equals, and thereby reduce memory usage. A weak interner allows the garbage collector to discard the canonical instance when all usages have been reclaimed. This special case of a weak keyed cache with Object.equals behavior is now supported, but hidden through an interface to make the behavior explicit and avoid misuses. For cases that want to cache by a canonical weak key to a value, the two type should be used in conjunction. Instead of incorrectly trying to combine into a single cache, use intern the key and use that for the cache lookup.
- Loading branch information
Showing
15 changed files
with
488 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
name: 'Dependency Review' | ||
on: [pull_request] | ||
|
||
permissions: | ||
contents: read | ||
|
||
jobs: | ||
dependency-review: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: 'Checkout Repository' | ||
uses: actions/checkout@v3 | ||
- name: 'Dependency Review' | ||
uses: actions/dependency-review-action@v1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
176 changes: 176 additions & 0 deletions
176
caffeine/src/main/java/com/github/benmanes/caffeine/cache/Interner.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
/* | ||
* Copyright 2022 Ben Manes. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package com.github.benmanes.caffeine.cache; | ||
|
||
import java.lang.ref.Reference; | ||
import java.lang.ref.ReferenceQueue; | ||
import java.util.Objects; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.ConcurrentMap; | ||
|
||
import com.github.benmanes.caffeine.cache.References.LookupKeyEqualsReference; | ||
import com.github.benmanes.caffeine.cache.References.WeakKeyEqualsReference; | ||
|
||
/** | ||
* Provides similar behavior to {@link String#intern} for any immutable type. | ||
* <p> | ||
* Note that {@code String.intern()} has some well-known performance limitations, and should | ||
* generally be avoided. Prefer {@link Interner#newWeakInterner} or another {@code Interner} | ||
* implementation even for {@code String} interning. | ||
* | ||
* @param <E> the type of elements | ||
* @author [email protected] (Ben Manes) | ||
*/ | ||
@FunctionalInterface | ||
public interface Interner<E extends Object> { | ||
|
||
/** | ||
* Chooses and returns the representative instance for any of a collection of instances that are | ||
* equal to each other. If two {@linkplain Object#equals equal} inputs are given to this method, | ||
* both calls will return the same instance. That is, {@code intern(a).equals(a)} always holds, | ||
* and {@code intern(a) == intern(b)} if and only if {@code a.equals(b)}. Note that {@code | ||
* intern(a)} is permitted to return one instance now and a different instance later if the | ||
* original interned instance was garbage-collected. | ||
* <p> | ||
* <b>Warning:</b> do not use with mutable objects. | ||
* | ||
* @param sample the element to add if absent | ||
* @return the representative instance, possibly the {@code sample} if absent | ||
* @throws NullPointerException if {@code sample} is null | ||
*/ | ||
E intern(E sample); | ||
|
||
/** | ||
* Returns a new thread-safe interner which retains a strong reference to each instance it has | ||
* interned, thus preventing these instances from being garbage-collected. | ||
* | ||
* @param <E> the type of elements | ||
* @return an interner for retrieving the canonical instance | ||
*/ | ||
static <E> Interner<E> newStrongInterner() { | ||
return new StrongInterner<>(); | ||
} | ||
|
||
/** | ||
* Returns a new thread-safe interner which retains a weak reference to each instance it has | ||
* interned, and so does not prevent these instances from being garbage-collected. | ||
* | ||
* @param <E> the type of elements | ||
* @return an interner for retrieving the canonical instance | ||
*/ | ||
static <E> Interner<E> newWeakInterner() { | ||
return new WeakInterner<>(); | ||
} | ||
} | ||
|
||
final class StrongInterner<E> implements Interner<E> { | ||
final ConcurrentMap<E, E> map; | ||
|
||
StrongInterner() { | ||
map = new ConcurrentHashMap<>(); | ||
} | ||
@Override public E intern(E sample) { | ||
E canonical = map.get(sample); | ||
if (canonical != null) { | ||
return canonical; | ||
} | ||
|
||
var value = map.putIfAbsent(sample, sample); | ||
if (value == null) { | ||
return sample; | ||
} | ||
return value; | ||
} | ||
} | ||
|
||
final class WeakInterner<E> implements Interner<E> { | ||
final BoundedLocalCache<E, Boolean> cache; | ||
|
||
WeakInterner() { | ||
cache = Caffeine.newWeakInterner(); | ||
} | ||
@Override public E intern(E sample) { | ||
for (;;) { | ||
E canonical = cache.getKey(sample); | ||
if (canonical != null) { | ||
return canonical; | ||
} | ||
|
||
var value = cache.putIfAbsent(sample, Boolean.TRUE); | ||
if (value == null) { | ||
return sample; | ||
} | ||
} | ||
} | ||
} | ||
|
||
@SuppressWarnings({"unchecked", "NullAway"}) | ||
final class Interned<K, V> extends Node<K, V> implements NodeFactory<K, V> { | ||
volatile Reference<?> keyReference; | ||
|
||
Interned() {} | ||
|
||
Interned(Reference<K> keyReference) { | ||
this.keyReference = keyReference; | ||
} | ||
@Override public K getKey() { | ||
return (K) keyReference.get(); | ||
} | ||
@Override public Object getKeyReference() { | ||
return keyReference; | ||
} | ||
@Override public V getValue() { | ||
return (V) Boolean.TRUE; | ||
} | ||
@Override public V getValueReference() { | ||
return (V) Boolean.TRUE; | ||
} | ||
@Override public void setValue(V value, ReferenceQueue<V> referenceQueue) {} | ||
@Override public boolean containsValue(Object value) { | ||
return Objects.equals(value, getValue()); | ||
} | ||
@Override public Node<K, V> newNode(K key, ReferenceQueue<K> keyReferenceQueue, | ||
V value, ReferenceQueue<V> valueReferenceQueue, int weight, long now) { | ||
return new Interned<>(new WeakKeyEqualsReference<>(key, keyReferenceQueue)); | ||
} | ||
@Override public Node<K, V> newNode(Object keyReference, V value, | ||
ReferenceQueue<V> valueReferenceQueue, int weight, long now) { | ||
return new Interned<>((Reference<K>) keyReference); | ||
} | ||
@Override public Object newLookupKey(Object key) { | ||
return new LookupKeyEqualsReference<>(key); | ||
} | ||
@Override public Object newReferenceKey(K key, ReferenceQueue<K> referenceQueue) { | ||
return new WeakKeyEqualsReference<K>(key, referenceQueue); | ||
} | ||
@Override public boolean isAlive() { | ||
Object keyRef = keyReference; | ||
return (keyRef != RETIRED_WEAK_KEY) && (keyRef != DEAD_WEAK_KEY); | ||
} | ||
@Override public boolean isRetired() { | ||
return (keyReference == RETIRED_WEAK_KEY); | ||
} | ||
@Override public void retire() { | ||
keyReference = RETIRED_WEAK_KEY; | ||
} | ||
@Override public boolean isDead() { | ||
return (keyReference == DEAD_WEAK_KEY); | ||
} | ||
@Override public void die() { | ||
keyReference.clear(); | ||
keyReference = DEAD_WEAK_KEY; | ||
} | ||
} |
Oops, something went wrong.