Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/com/sun/beans/util/Cache.java
38923 views
/*1* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package com.sun.beans.util;2526import java.lang.ref.ReferenceQueue;27import java.lang.ref.SoftReference;28import java.lang.ref.WeakReference;29import java.util.Objects;3031/**32* Hash table based implementation of the cache,33* which allows to use weak or soft references for keys and values.34* An entry in a {@code Cache} will automatically be removed35* when its key or value is no longer in ordinary use.36*37* @author Sergey Malenkov38* @since 1.839*/40public abstract class Cache<K,V> {41private static final int MAXIMUM_CAPACITY = 1 << 30; // maximum capacity MUST be a power of two <= 1<<304243private final boolean identity; // defines whether the identity comparison is used44private final Kind keyKind; // a reference kind for the cache keys45private final Kind valueKind; // a reference kind for the cache values4647private final ReferenceQueue<Object> queue = new ReferenceQueue<>(); // queue for references to remove4849private volatile CacheEntry<K,V>[] table = newTable(1 << 3); // table's length MUST be a power of two50private int threshold = 6; // the next size value at which to resize51private int size; // the number of key-value mappings contained in this map5253/**54* Creates a corresponding value for the specified key.55*56* @param key a key that can be used to create a value57* @return a corresponding value for the specified key58*/59public abstract V create(K key);6061/**62* Constructs an empty {@code Cache}.63* The default initial capacity is 8.64* The default load factor is 0.75.65*66* @param keyKind a reference kind for keys67* @param valueKind a reference kind for values68*69* @throws NullPointerException if {@code keyKind} or {@code valueKind} are {@code null}70*/71public Cache(Kind keyKind, Kind valueKind) {72this(keyKind, valueKind, false);73}7475/**76* Constructs an empty {@code Cache}77* with the specified comparison method.78* The default initial capacity is 8.79* The default load factor is 0.75.80*81* @param keyKind a reference kind for keys82* @param valueKind a reference kind for values83* @param identity defines whether reference-equality84* is used in place of object-equality85*86* @throws NullPointerException if {@code keyKind} or {@code valueKind} are {@code null}87*/88public Cache(Kind keyKind, Kind valueKind, boolean identity) {89Objects.requireNonNull(keyKind, "keyKind");90Objects.requireNonNull(valueKind, "valueKind");91this.keyKind = keyKind;92this.valueKind = valueKind;93this.identity = identity;94}9596/**97* Returns the value to which the specified key is mapped,98* or {@code null} if there is no mapping for the key.99*100* @param key the key whose cached value is to be returned101* @return a value to which the specified key is mapped,102* or {@code null} if there is no mapping for {@code key}103*104* @throws NullPointerException if {@code key} is {@code null}105* or corresponding value is {@code null}106*/107public final V get(K key) {108Objects.requireNonNull(key, "key");109removeStaleEntries();110int hash = hash(key);111// unsynchronized search improves performance112// the null value does not mean that there are no needed entry113CacheEntry<K,V>[] table = this.table; // unsynchronized access114V current = getEntryValue(key, hash, table[index(hash, table)]);115if (current != null) {116return current;117}118synchronized (this.queue) {119// synchronized search improves stability120// we must create and add new value if there are no needed entry121current = getEntryValue(key, hash, this.table[index(hash, this.table)]);122if (current != null) {123return current;124}125V value = create(key);126Objects.requireNonNull(value, "value");127int index = index(hash, this.table);128this.table[index] = new CacheEntry<>(hash, key, value, this.table[index]);129if (++this.size >= this.threshold) {130if (this.table.length == MAXIMUM_CAPACITY) {131this.threshold = Integer.MAX_VALUE;132} else {133removeStaleEntries();134table = newTable(this.table.length << 1);135transfer(this.table, table);136// If ignoring null elements and processing ref queue caused massive137// shrinkage, then restore old table. This should be rare, but avoids138// unbounded expansion of garbage-filled tables.139if (this.size >= this.threshold / 2) {140this.table = table;141this.threshold <<= 1;142} else {143transfer(table, this.table);144}145removeStaleEntries();146}147}148return value;149}150}151152/**153* Removes the cached value that corresponds to the specified key.154*155* @param key the key whose mapping is to be removed from this cache156*/157public final void remove(K key) {158if (key != null) {159synchronized (this.queue) {160removeStaleEntries();161int hash = hash(key);162int index = index(hash, this.table);163CacheEntry<K,V> prev = this.table[index];164CacheEntry<K,V> entry = prev;165while (entry != null) {166CacheEntry<K,V> next = entry.next;167if (entry.matches(hash, key)) {168if (entry == prev) {169this.table[index] = next;170} else {171prev.next = next;172}173entry.unlink();174break;175}176prev = entry;177entry = next;178}179}180}181}182183/**184* Removes all of the mappings from this cache.185* It will be empty after this call returns.186*/187public final void clear() {188synchronized (this.queue) {189int index = this.table.length;190while (0 < index--) {191CacheEntry<K,V> entry = this.table[index];192while (entry != null) {193CacheEntry<K,V> next = entry.next;194entry.unlink();195entry = next;196}197this.table[index] = null;198}199while (null != this.queue.poll()) {200// Clear out the reference queue.201}202}203}204205/**206* Retrieves object hash code and applies a supplemental hash function207* to the result hash, which defends against poor quality hash functions.208* This is critical because {@code Cache} uses power-of-two length hash tables,209* that otherwise encounter collisions for hashCodes that do not differ210* in lower bits.211*212* @param key the object which hash code is to be calculated213* @return a hash code value for the specified object214*/215private int hash(Object key) {216if (this.identity) {217int hash = System.identityHashCode(key);218return (hash << 1) - (hash << 8);219}220int hash = key.hashCode();221// This function ensures that hashCodes that differ only by222// constant multiples at each bit position have a bounded223// number of collisions (approximately 8 at default load factor).224hash ^= (hash >>> 20) ^ (hash >>> 12);225return hash ^ (hash >>> 7) ^ (hash >>> 4);226}227228/**229* Returns index of the specified hash code in the given table.230* Note that the table size must be a power of two.231*232* @param hash the hash code233* @param table the table234* @return an index of the specified hash code in the given table235*/236private static int index(int hash, Object[] table) {237return hash & (table.length - 1);238}239240/**241* Creates a new array for the cache entries.242*243* @param size requested capacity MUST be a power of two244* @return a new array for the cache entries245*/246@SuppressWarnings("unchecked")247private CacheEntry<K,V>[] newTable(int size) {248return (CacheEntry<K,V>[]) new CacheEntry[size];249}250251private V getEntryValue(K key, int hash, CacheEntry<K,V> entry) {252while (entry != null) {253if (entry.matches(hash, key)) {254return entry.value.getReferent();255}256entry = entry.next;257}258return null;259}260261private void removeStaleEntries() {262Object reference = this.queue.poll();263if (reference != null) {264synchronized (this.queue) {265do {266if (reference instanceof Ref) {267Ref ref = (Ref) reference;268@SuppressWarnings("unchecked")269CacheEntry<K,V> owner = (CacheEntry<K,V>) ref.getOwner();270if (owner != null) {271int index = index(owner.hash, this.table);272CacheEntry<K,V> prev = this.table[index];273CacheEntry<K,V> entry = prev;274while (entry != null) {275CacheEntry<K,V> next = entry.next;276if (entry == owner) {277if (entry == prev) {278this.table[index] = next;279} else {280prev.next = next;281}282entry.unlink();283break;284}285prev = entry;286entry = next;287}288}289}290reference = this.queue.poll();291}292while (reference != null);293}294}295}296297private void transfer(CacheEntry<K,V>[] oldTable, CacheEntry<K,V>[] newTable) {298int oldIndex = oldTable.length;299while (0 < oldIndex--) {300CacheEntry<K,V> entry = oldTable[oldIndex];301oldTable[oldIndex] = null;302while (entry != null) {303CacheEntry<K,V> next = entry.next;304if (entry.key.isStale() || entry.value.isStale()) {305entry.unlink();306} else {307int newIndex = index(entry.hash, newTable);308entry.next = newTable[newIndex];309newTable[newIndex] = entry;310}311entry = next;312}313}314}315316/**317* Represents a cache entry (key-value pair).318*/319private final class CacheEntry<K,V> {320private final int hash;321private final Ref<K> key;322private final Ref<V> value;323private volatile CacheEntry<K,V> next;324325/**326* Constructs an entry for the cache.327*328* @param hash the hash code calculated for the entry key329* @param key the entry key330* @param value the initial value of the entry331* @param next the next entry in a chain332*/333private CacheEntry(int hash, K key, V value, CacheEntry<K,V> next) {334this.hash = hash;335this.key = Cache.this.keyKind.create(this, key, Cache.this.queue);336this.value = Cache.this.valueKind.create(this, value, Cache.this.queue);337this.next = next;338}339340/**341* Determines whether the entry has the given key with the given hash code.342*343* @param hash an expected hash code344* @param object an object to be compared with the entry key345* @return {@code true} if the entry has the given key with the given hash code;346* {@code false} otherwise347*/348private boolean matches(int hash, Object object) {349if (this.hash != hash) {350return false;351}352Object key = this.key.getReferent();353return (key == object) || !Cache.this.identity && (key != null) && key.equals(object);354}355356/**357* Marks the entry as actually removed from the cache.358*/359private void unlink() {360this.next = null;361this.key.removeOwner();362this.value.removeOwner();363Cache.this.size--;364}365}366367/**368* Basic interface for references.369* It defines the operations common for the all kind of references.370*371* @param <T> the type of object to refer372*/373private static interface Ref<T> {374/**375* Returns the object that possesses information about the reference.376*377* @return the owner of the reference or {@code null} if the owner is unknown378*/379Object getOwner();380381/**382* Returns the object to refer.383*384* @return the referred object or {@code null} if it was collected385*/386T getReferent();387388/**389* Determines whether the referred object was taken by the garbage collector or not.390*391* @return {@code true} if the referred object was collected392*/393boolean isStale();394395/**396* Marks this reference as removed from the cache.397*/398void removeOwner();399}400401/**402* Represents a reference kind.403*/404public static enum Kind {405STRONG {406<T> Ref<T> create(Object owner, T value, ReferenceQueue<? super T> queue) {407return new Strong<>(owner, value);408}409},410SOFT {411<T> Ref<T> create(Object owner, T referent, ReferenceQueue<? super T> queue) {412return (referent == null)413? new Strong<>(owner, referent)414: new Soft<>(owner, referent, queue);415}416},417WEAK {418<T> Ref<T> create(Object owner, T referent, ReferenceQueue<? super T> queue) {419return (referent == null)420? new Strong<>(owner, referent)421: new Weak<>(owner, referent, queue);422}423};424425/**426* Creates a reference to the specified object.427*428* @param <T> the type of object to refer429* @param owner the owner of the reference, if needed430* @param referent the object to refer431* @param queue the queue to register the reference with,432* or {@code null} if registration is not required433* @return the reference to the specified object434*/435abstract <T> Ref<T> create(Object owner, T referent, ReferenceQueue<? super T> queue);436437/**438* This is an implementation of the {@link Cache.Ref} interface439* that uses the strong references that prevent their referents440* from being made finalizable, finalized, and then reclaimed.441*442* @param <T> the type of object to refer443*/444private static final class Strong<T> implements Ref<T> {445private Object owner;446private final T referent;447448/**449* Creates a strong reference to the specified object.450*451* @param owner the owner of the reference, if needed452* @param referent the non-null object to refer453*/454private Strong(Object owner, T referent) {455this.owner = owner;456this.referent = referent;457}458459/**460* Returns the object that possesses information about the reference.461*462* @return the owner of the reference or {@code null} if the owner is unknown463*/464public Object getOwner() {465return this.owner;466}467468/**469* Returns the object to refer.470*471* @return the referred object472*/473public T getReferent() {474return this.referent;475}476477/**478* Determines whether the referred object was taken by the garbage collector or not.479*480* @return {@code true} if the referred object was collected481*/482public boolean isStale() {483return false;484}485486/**487* Marks this reference as removed from the cache.488*/489public void removeOwner() {490this.owner = null;491}492}493494/**495* This is an implementation of the {@link Cache.Ref} interface496* that uses the soft references that are cleared at the discretion497* of the garbage collector in response to a memory request.498*499* @param <T> the type of object to refer500* @see java.lang.ref.SoftReference501*/502private static final class Soft<T> extends SoftReference<T> implements Ref<T> {503private Object owner;504505/**506* Creates a soft reference to the specified object.507*508* @param owner the owner of the reference, if needed509* @param referent the non-null object to refer510* @param queue the queue to register the reference with,511* or {@code null} if registration is not required512*/513private Soft(Object owner, T referent, ReferenceQueue<? super T> queue) {514super(referent, queue);515this.owner = owner;516}517518/**519* Returns the object that possesses information about the reference.520*521* @return the owner of the reference or {@code null} if the owner is unknown522*/523public Object getOwner() {524return this.owner;525}526527/**528* Returns the object to refer.529*530* @return the referred object or {@code null} if it was collected531*/532public T getReferent() {533return get();534}535536/**537* Determines whether the referred object was taken by the garbage collector or not.538*539* @return {@code true} if the referred object was collected540*/541public boolean isStale() {542return null == get();543}544545/**546* Marks this reference as removed from the cache.547*/548public void removeOwner() {549this.owner = null;550}551}552553/**554* This is an implementation of the {@link Cache.Ref} interface555* that uses the weak references that do not prevent their referents556* from being made finalizable, finalized, and then reclaimed.557*558* @param <T> the type of object to refer559* @see java.lang.ref.WeakReference560*/561private static final class Weak<T> extends WeakReference<T> implements Ref<T> {562private Object owner;563564/**565* Creates a weak reference to the specified object.566*567* @param owner the owner of the reference, if needed568* @param referent the non-null object to refer569* @param queue the queue to register the reference with,570* or {@code null} if registration is not required571*/572private Weak(Object owner, T referent, ReferenceQueue<? super T> queue) {573super(referent, queue);574this.owner = owner;575}576577/**578* Returns the object that possesses information about the reference.579*580* @return the owner of the reference or {@code null} if the owner is unknown581*/582public Object getOwner() {583return this.owner;584}585586/**587* Returns the object to refer.588*589* @return the referred object or {@code null} if it was collected590*/591public T getReferent() {592return get();593}594595/**596* Determines whether the referred object was taken by the garbage collector or not.597*598* @return {@code true} if the referred object was collected599*/600public boolean isStale() {601return null == get();602}603604/**605* Marks this reference as removed from the cache.606*/607public void removeOwner() {608this.owner = null;609}610}611}612}613614615