1 /*
   2  * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 import java.io.*;
  28 import java.util.function.BiConsumer;
  29 import java.util.function.BiFunction;
  30 
  31 /**
  32  * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
  33  * with predictable iteration order.  This implementation differs from
  34  * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
  35  * all of its entries.  This linked list defines the iteration ordering,
  36  * which is normally the order in which keys were inserted into the map
  37  * (<i>insertion-order</i>).  Note that insertion order is not affected
  38  * if a key is <i>re-inserted</i> into the map.  (A key <tt>k</tt> is
  39  * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
  40  * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
  41  * the invocation.)
  42  *
  43  * <p>This implementation spares its clients from the unspecified, generally
  44  * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
  45  * without incurring the increased cost associated with {@link TreeMap}.  It
  46  * can be used to produce a copy of a map that has the same order as the
  47  * original, regardless of the original map's implementation:
  48  * <pre>
  49  *     void foo(Map m) {
  50  *         Map copy = new LinkedHashMap(m);
  51  *         ...
  52  *     }
  53  * </pre>
  54  * This technique is particularly useful if a module takes a map on input,
  55  * copies it, and later returns results whose order is determined by that of
  56  * the copy.  (Clients generally appreciate having things returned in the same
  57  * order they were presented.)
  58  *
  59  * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
  60  * provided to create a <tt>LinkedHashMap</tt> whose order of iteration is the
  61  * order in which its entries were last accessed, from least-recently accessed
  62  * to most-recently (<i>access-order</i>).  This kind of map is well-suited to
  63  * building LRU caches.  Invoking the <tt>put</tt> or <tt>get</tt> method
  64  * results in an access to the corresponding entry (assuming it exists after
  65  * the invocation completes).  The <tt>putAll</tt> method generates one entry
  66  * access for each mapping in the specified map, in the order that key-value
  67  * mappings are provided by the specified map's entry set iterator.  <i>No
  68  * other methods generate entry accesses.</i> In particular, operations on
  69  * collection-views do <i>not</i> affect the order of iteration of the backing
  70  * map.
  71  *
  72  * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
  73  * impose a policy for removing stale mappings automatically when new mappings
  74  * are added to the map.
  75  *
  76  * <p>This class provides all of the optional <tt>Map</tt> operations, and
  77  * permits null elements.  Like <tt>HashMap</tt>, it provides constant-time
  78  * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
  79  * <tt>remove</tt>), assuming the hash function disperses elements
  80  * properly among the buckets.  Performance is likely to be just slightly
  81  * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
  82  * linked list, with one exception: Iteration over the collection-views
  83  * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
  84  * of the map, regardless of its capacity.  Iteration over a <tt>HashMap</tt>
  85  * is likely to be more expensive, requiring time proportional to its
  86  * <i>capacity</i>.
  87  *
  88  * <p>A linked hash map has two parameters that affect its performance:
  89  * <i>initial capacity</i> and <i>load factor</i>.  They are defined precisely
  90  * as for <tt>HashMap</tt>.  Note, however, that the penalty for choosing an
  91  * excessively high value for initial capacity is less severe for this class
  92  * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
  93  * by capacity.
  94  *
  95  * <p><strong>Note that this implementation is not synchronized.</strong>
  96  * If multiple threads access a linked hash map concurrently, and at least
  97  * one of the threads modifies the map structurally, it <em>must</em> be
  98  * synchronized externally.  This is typically accomplished by
  99  * synchronizing on some object that naturally encapsulates the map.
 100  *
 101  * If no such object exists, the map should be "wrapped" using the
 102  * {@link Collections#synchronizedMap Collections.synchronizedMap}
 103  * method.  This is best done at creation time, to prevent accidental
 104  * unsynchronized access to the map:<pre>
 105  *   Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre>
 106  *
 107  * A structural modification is any operation that adds or deletes one or more
 108  * mappings or, in the case of access-ordered linked hash maps, affects
 109  * iteration order.  In insertion-ordered linked hash maps, merely changing
 110  * the value associated with a key that is already contained in the map is not
 111  * a structural modification.  <strong>In access-ordered linked hash maps,
 112  * merely querying the map with <tt>get</tt> is a structural
 113  * modification.</strong>)
 114  *
 115  * <p>The iterators returned by the <tt>iterator</tt> method of the collections
 116  * returned by all of this class's collection view methods are
 117  * <em>fail-fast</em>: if the map is structurally modified at any time after
 118  * the iterator is created, in any way except through the iterator's own
 119  * <tt>remove</tt> method, the iterator will throw a {@link
 120  * ConcurrentModificationException}.  Thus, in the face of concurrent
 121  * modification, the iterator fails quickly and cleanly, rather than risking
 122  * arbitrary, non-deterministic behavior at an undetermined time in the future.
 123  *
 124  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 125  * as it is, generally speaking, impossible to make any hard guarantees in the
 126  * presence of unsynchronized concurrent modification.  Fail-fast iterators
 127  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 128  * Therefore, it would be wrong to write a program that depended on this
 129  * exception for its correctness:   <i>the fail-fast behavior of iterators
 130  * should be used only to detect bugs.</i>
 131  *
 132  * <p>This class is a member of the
 133  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 134  * Java Collections Framework</a>.
 135  *
 136  * @param <K> the type of keys maintained by this map
 137  * @param <V> the type of mapped values
 138  *
 139  * @author  Josh Bloch
 140  * @see     Object#hashCode()
 141  * @see     Collection
 142  * @see     Map
 143  * @see     HashMap
 144  * @see     TreeMap
 145  * @see     Hashtable
 146  * @since   1.4
 147  */
 148 
 149 public class LinkedHashMap<K,V>
 150     extends HashMap<K,V>
 151     implements Map<K,V>
 152 {
 153 
 154     private static final long serialVersionUID = 3801124242820219131L;
 155 
 156     /**
 157      * The head of the doubly linked list.
 158      */
 159     private transient Entry<K,V> header;
 160 
 161     /**
 162      * The iteration ordering method for this linked hash map: <tt>true</tt>
 163      * for access-order, <tt>false</tt> for insertion-order.
 164      *
 165      * @serial
 166      */
 167     private final boolean accessOrder;
 168 
 169     /**
 170      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
 171      * with the specified initial capacity and load factor.
 172      *
 173      * @param  initialCapacity the initial capacity
 174      * @param  loadFactor      the load factor
 175      * @throws IllegalArgumentException if the initial capacity is negative
 176      *         or the load factor is nonpositive
 177      */
 178     public LinkedHashMap(int initialCapacity, float loadFactor) {
 179         super(initialCapacity, loadFactor);
 180         accessOrder = false;
 181     }
 182 
 183     /**
 184      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
 185      * with the specified initial capacity and a default load factor (0.75).
 186      *
 187      * @param  initialCapacity the initial capacity
 188      * @throws IllegalArgumentException if the initial capacity is negative
 189      */
 190     public LinkedHashMap(int initialCapacity) {
 191         super(initialCapacity);
 192         accessOrder = false;
 193     }
 194 
 195     /**
 196      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
 197      * with the default initial capacity (16) and load factor (0.75).
 198      */
 199     public LinkedHashMap() {
 200         super();
 201         accessOrder = false;
 202     }
 203 
 204     /**
 205      * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
 206      * the same mappings as the specified map.  The <tt>LinkedHashMap</tt>
 207      * instance is created with a default load factor (0.75) and an initial
 208      * capacity sufficient to hold the mappings in the specified map.
 209      *
 210      * @param  m the map whose mappings are to be placed in this map
 211      * @throws NullPointerException if the specified map is null
 212      */
 213     public LinkedHashMap(Map<? extends K, ? extends V> m) {
 214         super(m);
 215         accessOrder = false;
 216     }
 217 
 218     /**
 219      * Constructs an empty <tt>LinkedHashMap</tt> instance with the
 220      * specified initial capacity, load factor and ordering mode.
 221      *
 222      * @param  initialCapacity the initial capacity
 223      * @param  loadFactor      the load factor
 224      * @param  accessOrder     the ordering mode - <tt>true</tt> for
 225      *         access-order, <tt>false</tt> for insertion-order
 226      * @throws IllegalArgumentException if the initial capacity is negative
 227      *         or the load factor is nonpositive
 228      */
 229     public LinkedHashMap(int initialCapacity,
 230                          float loadFactor,
 231                          boolean accessOrder) {
 232         super(initialCapacity, loadFactor);
 233         this.accessOrder = accessOrder;
 234     }
 235 
 236     /**
 237      * Called by superclass constructors and pseudoconstructors (clone,
 238      * readObject) before any entries are inserted into the map.  Initializes
 239      * the chain.
 240      */
 241     @Override
 242     void init() {
 243         header = new Entry<>(-1, null, null, null);
 244         header.before = header.after = header;
 245     }
 246 
 247     /**
 248      * Returns <tt>true</tt> if this map maps one or more keys to the
 249      * specified value.
 250      *
 251      * @param value value whose presence in this map is to be tested
 252      * @return <tt>true</tt> if this map maps one or more keys to the
 253      *         specified value
 254      */
 255     public boolean containsValue(Object value) {
 256         // Overridden to take advantage of faster iterator
 257         if (value==null) {
 258             for (Entry<?,?> e = header.after; e != header; e = e.after)
 259                 if (e.value==null)
 260                     return true;
 261         } else {
 262             for (Entry<?,?> e = header.after; e != header; e = e.after)
 263                 if (value.equals(e.value))
 264                     return true;
 265         }
 266         return false;
 267     }
 268 
 269     /**
 270      * Returns the value to which the specified key is mapped,
 271      * or {@code null} if this map contains no mapping for the key.
 272      *
 273      * <p>More formally, if this map contains a mapping from a key
 274      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 275      * key.equals(k))}, then this method returns {@code v}; otherwise
 276      * it returns {@code null}.  (There can be at most one such mapping.)
 277      *
 278      * <p>A return value of {@code null} does not <i>necessarily</i>
 279      * indicate that the map contains no mapping for the key; it's also
 280      * possible that the map explicitly maps the key to {@code null}.
 281      * The {@link #containsKey containsKey} operation may be used to
 282      * distinguish these two cases.
 283      */
 284     public V get(Object key) {
 285         Entry<K,V> e = (Entry<K,V>)getEntry(key);
 286         if (e == null)
 287             return null;
 288         e.recordAccess(this);
 289         return e.value;
 290     }
 291 
 292     /**
 293      * Removes all of the mappings from this map.
 294      * The map will be empty after this call returns.
 295      */
 296     public void clear() {
 297         super.clear();
 298         header.before = header.after = header;
 299     }
 300 
 301     @Override
 302     public void forEach(BiConsumer<? super K, ? super V> action) {
 303         Objects.requireNonNull(action);
 304         int expectedModCount = modCount;
 305         for (Entry<K,V> entry = header.after; entry != header; entry = entry.after) {
 306             if (expectedModCount != modCount) {
 307                 throw new ConcurrentModificationException();
 308             }
 309            action.accept(entry.key, entry.value);
 310         }
 311     }
 312 
 313     @Override
 314     public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
 315         Objects.requireNonNull(function);
 316         int expectedModCount = modCount;
 317         for (Entry<K,V> entry = header.after; entry != header; entry = entry.after) {
 318             if (expectedModCount != modCount) {
 319                 throw new ConcurrentModificationException();
 320             }
 321            entry.value = function.apply(entry.key, entry.value);
 322         }
 323     }
 324 
 325     /**
 326      * LinkedHashMap entry.
 327      */
 328     private static class Entry<K,V> extends HashMap.Entry<K,V> {
 329         // These fields comprise the doubly linked list used for iteration.
 330         Entry<K,V> before, after;
 331 
 332         Entry(int hash, K key, V value, Object next) {
 333             super(hash, key, value, next);
 334         }
 335 
 336         /**
 337          * Removes this entry from the linked list.
 338          */
 339         private void remove() {
 340             before.after = after;
 341             after.before = before;
 342         }
 343 
 344         /**
 345          * Inserts this entry before the specified existing entry in the list.
 346          */
 347         private void addBefore(Entry<K,V> existingEntry) {
 348             after  = existingEntry;
 349             before = existingEntry.before;
 350             before.after = this;
 351             after.before = this;
 352         }
 353 
 354         /**
 355          * This method is invoked by the superclass whenever the value
 356          * of a pre-existing entry is read by Map.get or modified by Map.put.
 357          * If the enclosing Map is access-ordered, it moves the entry
 358          * to the end of the list; otherwise, it does nothing.
 359          */
 360         void recordAccess(HashMap<K,V> m) {
 361             LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
 362             if (lm.accessOrder) {
 363                 lm.modCount++;
 364                 remove();
 365                 addBefore(lm.header);
 366             }
 367         }
 368 
 369         void recordRemoval(HashMap<K,V> m) {
 370             remove();
 371         }
 372     }
 373 
 374     private abstract class LinkedHashIterator<T> implements Iterator<T> {
 375         Entry<K,V> nextEntry    = header.after;
 376         Entry<K,V> lastReturned = null;
 377 
 378         /**
 379          * The modCount value that the iterator believes that the backing
 380          * List should have.  If this expectation is violated, the iterator
 381          * has detected concurrent modification.
 382          */
 383         int expectedModCount = modCount;
 384 
 385         public boolean hasNext() {
 386             return nextEntry != header;
 387         }
 388 
 389         public void remove() {
 390             if (lastReturned == null)
 391                 throw new IllegalStateException();
 392             if (modCount != expectedModCount)
 393                 throw new ConcurrentModificationException();
 394 
 395             LinkedHashMap.this.remove(lastReturned.key);
 396             lastReturned = null;
 397             expectedModCount = modCount;
 398         }
 399 
 400         Entry<K,V> nextEntry() {
 401             if (modCount != expectedModCount)
 402                 throw new ConcurrentModificationException();
 403             if (nextEntry == header)
 404                 throw new NoSuchElementException();
 405 
 406             Entry<K,V> e = lastReturned = nextEntry;
 407             nextEntry = e.after;
 408             return e;
 409         }
 410     }
 411 
 412     private class KeyIterator extends LinkedHashIterator<K> {
 413         public K next() { return nextEntry().getKey(); }
 414     }
 415 
 416     private class ValueIterator extends LinkedHashIterator<V> {
 417         public V next() { return nextEntry().value; }
 418     }
 419 
 420     private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
 421         public Map.Entry<K,V> next() { return nextEntry(); }
 422     }
 423 
 424     // These Overrides alter the behavior of superclass view iterator() methods
 425     Iterator<K> newKeyIterator()   { return new KeyIterator();   }
 426     Iterator<V> newValueIterator() { return new ValueIterator(); }
 427     Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
 428 
 429     /**
 430      * This override alters behavior of superclass put method. It causes newly
 431      * allocated entry to get inserted at the end of the linked list and
 432      * removes the eldest entry if appropriate.
 433      */
 434     @Override
 435     void addEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
 436         super.addEntry(hash, key, value, bucketIndex, checkIfNeedTree);
 437 
 438         // Remove eldest entry if instructed
 439         Entry<K,V> eldest = header.after;
 440         if (removeEldestEntry(eldest)) {
 441             removeEntryForKey(eldest.key);
 442         }
 443     }
 444 
 445     /*
 446      * Create a new LinkedHashMap.Entry and setup the before/after pointers
 447      */
 448     @Override
 449     HashMap.Entry<K,V> newEntry(int hash, K key, V value, Object next) {
 450         Entry<K,V> newEntry = new Entry<>(hash, key, value, next);
 451         newEntry.addBefore(header);
 452         return newEntry;
 453     }
 454 
 455     /**
 456      * Returns <tt>true</tt> if this map should remove its eldest entry.
 457      * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
 458      * inserting a new entry into the map.  It provides the implementor
 459      * with the opportunity to remove the eldest entry each time a new one
 460      * is added.  This is useful if the map represents a cache: it allows
 461      * the map to reduce memory consumption by deleting stale entries.
 462      *
 463      * <p>Sample use: this override will allow the map to grow up to 100
 464      * entries and then delete the eldest entry each time a new entry is
 465      * added, maintaining a steady state of 100 entries.
 466      * <pre>{@code
 467      *     private static final int MAX_ENTRIES = 100;
 468      *
 469      *     protected boolean removeEldestEntry(Map.Entry eldest) {
 470      *        return size() > MAX_ENTRIES;
 471      *     }
 472      * }</pre>
 473      *
 474      * <p>This method typically does not modify the map in any way,
 475      * instead allowing the map to modify itself as directed by its
 476      * return value.  It <i>is</i> permitted for this method to modify
 477      * the map directly, but if it does so, it <i>must</i> return
 478      * <tt>false</tt> (indicating that the map should not attempt any
 479      * further modification).  The effects of returning <tt>true</tt>
 480      * after modifying the map from within this method are unspecified.
 481      *
 482      * <p>This implementation merely returns <tt>false</tt> (so that this
 483      * map acts like a normal map - the eldest element is never removed).
 484      *
 485      * @param    eldest The least recently inserted entry in the map, or if
 486      *           this is an access-ordered map, the least recently accessed
 487      *           entry.  This is the entry that will be removed it this
 488      *           method returns <tt>true</tt>.  If the map was empty prior
 489      *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
 490      *           in this invocation, this will be the entry that was just
 491      *           inserted; in other words, if the map contains a single
 492      *           entry, the eldest entry is also the newest.
 493      * @return   <tt>true</tt> if the eldest entry should be removed
 494      *           from the map; <tt>false</tt> if it should be retained.
 495      */
 496     protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
 497         return false;
 498     }
 499 }