Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/misc/Cache.java
38829 views
/*1* Copyright (c) 1995, 1996, 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*/2425package sun.misc;2627import java.util.Dictionary;28import java.util.Enumeration;29import java.util.NoSuchElementException;3031/**32* Caches the collision list.33*/34class CacheEntry extends Ref {35int hash;36Object key;37CacheEntry next;38public Object reconstitute() {39return null;40}41}4243/**44* The Cache class. Maps keys to values. Any object can be used as45* a key and/or value. This is very similar to the Hashtable46* class, except that after putting an object into the Cache,47* it is not guaranteed that a subsequent get will return it.48* The Cache will automatically remove entries if memory is49* getting tight and if the entry is not referenced from outside50* the Cache.<p>51*52* To sucessfully store and retrieve objects from a hash table the53* object used as the key must implement the hashCode() and equals()54* methods.<p>55*56* This example creates a Cache of numbers. It uses the names of57* the numbers as keys:58* <pre>59* Cache numbers = new Cache();60* numbers.put("one", new Integer(1));61* numbers.put("two", new Integer(1));62* numbers.put("three", new Integer(1));63* </pre>64* To retrieve a number use:65* <pre>66* Integer n = (Integer)numbers.get("two");67* if (n != null) {68* System.out.println("two = " + n);69* }70* </pre>71*72* @see java.lang.Object#hashCode73* @see java.lang.Object#equals74* @see sun.misc.Ref75*/76public77class Cache extends Dictionary {78/**79* The hash table data.80*/81private CacheEntry table[];8283/**84* The total number of entries in the hash table.85*/86private int count;8788/**89* Rehashes the table when count exceeds this threshold.90*/91private int threshold;9293/**94* The load factor for the hashtable.95*/96private float loadFactor;9798private void init(int initialCapacity, float loadFactor) {99if ((initialCapacity <= 0) || (loadFactor <= 0.0)) {100throw new IllegalArgumentException();101}102this.loadFactor = loadFactor;103table = new CacheEntry[initialCapacity];104threshold = (int) (initialCapacity * loadFactor);105}106107/**108* Constructs a new, empty Cache with the specified initial109* capacity and the specified load factor.110* @param initialCapacity the initial number of buckets111* @param loadFactor a number between 0.0 and 1.0, it defines112* the threshold for rehashing the Cache into113* a bigger one.114* @exception IllegalArgumentException If the initial capacity115* is less than or equal to zero.116* @exception IllegalArgumentException If the load factor is117* less than or equal to zero.118*/119public Cache (int initialCapacity, float loadFactor) {120init(initialCapacity, loadFactor);121}122123/**124* Constructs a new, empty Cache with the specified initial125* capacity.126* @param initialCapacity the initial number of buckets127*/128public Cache (int initialCapacity) {129init(initialCapacity, 0.75f);130}131132/**133* Constructs a new, empty Cache. A default capacity and load factor134* is used. Note that the Cache will automatically grow when it gets135* full.136*/137public Cache () {138try {139init(101, 0.75f);140} catch (IllegalArgumentException ex) {141// This should never happen142throw new Error("panic");143}144}145146/**147* Returns the number of elements contained within the Cache.148*/149public int size() {150return count;151}152153/**154* Returns true if the Cache contains no elements.155*/156public boolean isEmpty() {157return count == 0;158}159160/**161* Returns an enumeration of the Cache's keys.162* @see Cache#elements163* @see Enumeration164*/165public synchronized Enumeration keys() {166return new CacheEnumerator(table, true);167}168169/**170* Returns an enumeration of the elements. Use the Enumeration methods171* on the returned object to fetch the elements sequentially.172* @see Cache#keys173* @see Enumeration174*/175public synchronized Enumeration elements() {176return new CacheEnumerator(table, false);177}178179/**180* Gets the object associated with the specified key in the Cache.181* @param key the key in the hash table182* @returns the element for the key or null if the key183* is not defined in the hash table.184* @see Cache#put185*/186public synchronized Object get(Object key) {187CacheEntry tab[] = table;188int hash = key.hashCode();189int index = (hash & 0x7FFFFFFF) % tab.length;190for (CacheEntry e = tab[index]; e != null; e = e.next) {191if ((e.hash == hash) && e.key.equals(key)) {192return e.check();193}194}195return null;196}197198/**199* Rehashes the contents of the table into a bigger table.200* This is method is called automatically when the Cache's201* size exceeds the threshold.202*/203protected void rehash() {204int oldCapacity = table.length;205CacheEntry oldTable[] = table;206207int newCapacity = oldCapacity * 2 + 1;208CacheEntry newTable[] = new CacheEntry[newCapacity];209210threshold = (int) (newCapacity * loadFactor);211table = newTable;212213// System.out.println("rehash old=" + oldCapacity + ", new=" +214// newCapacity + ", thresh=" + threshold + ", count=" + count);215216for (int i = oldCapacity; i-- > 0;) {217for (CacheEntry old = oldTable[i]; old != null;) {218CacheEntry e = old;219old = old.next;220if (e.check() != null) {221int index = (e.hash & 0x7FFFFFFF) % newCapacity;222e.next = newTable[index];223newTable[index] = e;224} else225count--; /* remove entries that have disappeared */226}227}228}229230/**231* Puts the specified element into the Cache, using the specified232* key. The element may be retrieved by doing a get() with the same233* key. The key and the element cannot be null.234* @param key the specified hashtable key235* @param value the specified element236* @return the old value of the key, or null if it did not have one.237* @exception NullPointerException If the value of the specified238* element is null.239* @see Cache#get240*/241public synchronized Object put(Object key, Object value) {242// Make sure the value is not null243if (value == null) {244throw new NullPointerException();245}246// Makes sure the key is not already in the cache.247CacheEntry tab[] = table;248int hash = key.hashCode();249int index = (hash & 0x7FFFFFFF) % tab.length;250CacheEntry ne = null;251for (CacheEntry e = tab[index]; e != null; e = e.next) {252if ((e.hash == hash) && e.key.equals(key)) {253Object old = e.check();254e.setThing(value);255return old;256} else if (e.check() == null)257ne = e; /* reuse old flushed value */258}259260if (count >= threshold) {261// Rehash the table if the threshold is exceeded262rehash();263return put(key, value);264}265// Creates the new entry.266if (ne == null) {267ne = new CacheEntry ();268ne.next = tab[index];269tab[index] = ne;270count++;271}272ne.hash = hash;273ne.key = key;274ne.setThing(value);275return null;276}277278/**279* Removes the element corresponding to the key. Does nothing if the280* key is not present.281* @param key the key that needs to be removed282* @return the value of key, or null if the key was not found.283*/284public synchronized Object remove(Object key) {285CacheEntry tab[] = table;286int hash = key.hashCode();287int index = (hash & 0x7FFFFFFF) % tab.length;288for (CacheEntry e = tab[index], prev = null; e != null; prev = e, e = e.next) {289if ((e.hash == hash) && e.key.equals(key)) {290if (prev != null) {291prev.next = e.next;292} else {293tab[index] = e.next;294}295count--;296return e.check();297}298}299return null;300}301}302303/**304* A Cache enumerator class. This class should remain opaque305* to the client. It will use the Enumeration interface.306*/307class CacheEnumerator implements Enumeration {308boolean keys;309int index;310CacheEntry table[];311CacheEntry entry;312313CacheEnumerator (CacheEntry table[], boolean keys) {314this.table = table;315this.keys = keys;316this.index = table.length;317}318319public boolean hasMoreElements() {320while (index >= 0) {321while (entry != null)322if (entry.check() != null)323return true;324else325entry = entry.next;326while (--index >= 0 && (entry = table[index]) == null) ;327}328return false;329}330331public Object nextElement() {332while (index >= 0) {333if (entry == null)334while (--index >= 0 && (entry = table[index]) == null) ;335if (entry != null) {336CacheEntry e = entry;337entry = e.next;338if (e.check() != null)339return keys ? e.key : e.check();340}341}342throw new NoSuchElementException("CacheEnumerator");343}344345}346347348