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