• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.collect;
16 
17 import static com.google.common.base.Preconditions.checkArgument;
18 import static com.google.common.base.Preconditions.checkNotNull;
19 import static com.google.common.base.Preconditions.checkState;
20 
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.annotations.GwtIncompatible;
23 import com.google.common.base.Ascii;
24 import com.google.common.base.Equivalence;
25 import com.google.common.base.MoreObjects;
26 import com.google.common.collect.MapMakerInternalMap.Strength;
27 import com.google.errorprone.annotations.CanIgnoreReturnValue;
28 import java.lang.ref.WeakReference;
29 import java.util.ConcurrentModificationException;
30 import java.util.Map;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33 import javax.annotation.CheckForNull;
34 
35 /**
36  * A builder of {@link ConcurrentMap} instances that can have keys or values automatically wrapped
37  * in {@linkplain WeakReference weak} references.
38  *
39  * <p>Usage example:
40  *
41  * <pre>{@code
42  * ConcurrentMap<Request, Stopwatch> timers = new MapMaker()
43  *     .concurrencyLevel(4)
44  *     .weakKeys()
45  *     .makeMap();
46  * }</pre>
47  *
48  * <p>These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent
49  * map that behaves similarly to a {@link ConcurrentHashMap}.
50  *
51  * <p>The returned map is implemented as a hash table with similar performance characteristics to
52  * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap}
53  * interface. It does not permit null keys or values.
54  *
55  * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals
56  * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was
57  * specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link
58  * #weakValues} was specified, the map uses identity comparisons for values.
59  *
60  * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means
61  * that they are safe for concurrent use, but if other threads modify the map after the iterator is
62  * created, it is undefined which of these changes, if any, are reflected in that iterator. These
63  * iterators never throw {@link ConcurrentModificationException}.
64  *
65  * <p>If {@link #weakKeys} or {@link #weakValues} are requested, it is possible for a key or value
66  * present in the map to be reclaimed by the garbage collector. Entries with reclaimed keys or
67  * values may be removed from the map on each map modification or on occasional map accesses; such
68  * entries may be counted by {@link Map#size}, but will never be visible to read or write
69  * operations. A partially-reclaimed entry is never exposed to the user. Any {@link Map.Entry}
70  * instance retrieved from the map's {@linkplain Map#entrySet entry set} is a snapshot of that
71  * entry's state at the time of retrieval; such entries do, however, support {@link
72  * Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key.
73  *
74  * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all
75  * the configuration properties of the original map. During deserialization, if the original map had
76  * used weak references, the entries are reconstructed as they were, but it's not unlikely they'll
77  * be quickly garbage-collected before they are ever accessed.
78  *
79  * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link
80  * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code
81  * WeakHashMap} uses {@link Object#equals}.
82  *
83  * @author Bob Lee
84  * @author Charles Fry
85  * @author Kevin Bourrillion
86  * @since 2.0
87  */
88 @GwtCompatible(emulated = true)
89 @ElementTypesAreNonnullByDefault
90 public final class MapMaker {
91   private static final int DEFAULT_INITIAL_CAPACITY = 16;
92   private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
93 
94   static final int UNSET_INT = -1;
95 
96   // TODO(kevinb): dispense with this after benchmarking
97   boolean useCustomMap;
98 
99   int initialCapacity = UNSET_INT;
100   int concurrencyLevel = UNSET_INT;
101 
102   @CheckForNull Strength keyStrength;
103   @CheckForNull Strength valueStrength;
104 
105   @CheckForNull Equivalence<Object> keyEquivalence;
106 
107   /**
108    * Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong
109    * values, and no automatic eviction of any kind.
110    */
MapMaker()111   public MapMaker() {}
112 
113   /**
114    * Sets a custom {@code Equivalence} strategy for comparing keys.
115    *
116    * <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link
117    * #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is
118    * used is in {@link Interners.WeakInterner}.
119    */
120   @CanIgnoreReturnValue
121   @GwtIncompatible // To be supported
keyEquivalence(Equivalence<Object> equivalence)122   MapMaker keyEquivalence(Equivalence<Object> equivalence) {
123     checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
124     keyEquivalence = checkNotNull(equivalence);
125     this.useCustomMap = true;
126     return this;
127   }
128 
getKeyEquivalence()129   Equivalence<Object> getKeyEquivalence() {
130     return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
131   }
132 
133   /**
134    * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
135    * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
136    * having a hash table of size eight. Providing a large enough estimate at construction time
137    * avoids the need for expensive resizing operations later, but setting this value unnecessarily
138    * high wastes memory.
139    *
140    * @throws IllegalArgumentException if {@code initialCapacity} is negative
141    * @throws IllegalStateException if an initial capacity was already set
142    */
143   @CanIgnoreReturnValue
initialCapacity(int initialCapacity)144   public MapMaker initialCapacity(int initialCapacity) {
145     checkState(
146         this.initialCapacity == UNSET_INT,
147         "initial capacity was already set to %s",
148         this.initialCapacity);
149     checkArgument(initialCapacity >= 0);
150     this.initialCapacity = initialCapacity;
151     return this;
152   }
153 
getInitialCapacity()154   int getInitialCapacity() {
155     return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
156   }
157 
158   /**
159    * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
160    * table is internally partitioned to try to permit the indicated number of concurrent updates
161    * without contention. Because assignment of entries to these partitions is not necessarily
162    * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
163    * accommodate as many threads as will ever concurrently modify the table. Using a significantly
164    * higher value than you need can waste space and time, and a significantly lower value can lead
165    * to thread contention. But overestimates and underestimates within an order of magnitude do not
166    * usually have much noticeable impact. A value of one permits only one thread to modify the map
167    * at a time, but since read operations can proceed concurrently, this still yields higher
168    * concurrency than full synchronization. Defaults to 4.
169    *
170    * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
171    * change again in the future. If you care about this value, you should always choose it
172    * explicitly.
173    *
174    * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
175    * @throws IllegalStateException if a concurrency level was already set
176    */
177   @CanIgnoreReturnValue
concurrencyLevel(int concurrencyLevel)178   public MapMaker concurrencyLevel(int concurrencyLevel) {
179     checkState(
180         this.concurrencyLevel == UNSET_INT,
181         "concurrency level was already set to %s",
182         this.concurrencyLevel);
183     checkArgument(concurrencyLevel > 0);
184     this.concurrencyLevel = concurrencyLevel;
185     return this;
186   }
187 
getConcurrencyLevel()188   int getConcurrencyLevel() {
189     return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
190   }
191 
192   /**
193    * Specifies that each key (not value) stored in the map should be wrapped in a {@link
194    * WeakReference} (by default, strong references are used).
195    *
196    * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
197    * comparison to determine equality of keys, which is a technical violation of the {@link Map}
198    * specification, and may not be what you expect.
199    *
200    * @throws IllegalStateException if the key strength was already set
201    * @see WeakReference
202    */
203   @CanIgnoreReturnValue
204   @GwtIncompatible // java.lang.ref.WeakReference
weakKeys()205   public MapMaker weakKeys() {
206     return setKeyStrength(Strength.WEAK);
207   }
208 
setKeyStrength(Strength strength)209   MapMaker setKeyStrength(Strength strength) {
210     checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
211     keyStrength = checkNotNull(strength);
212     if (strength != Strength.STRONG) {
213       // STRONG could be used during deserialization.
214       useCustomMap = true;
215     }
216     return this;
217   }
218 
getKeyStrength()219   Strength getKeyStrength() {
220     return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
221   }
222 
223   /**
224    * Specifies that each value (not key) stored in the map should be wrapped in a {@link
225    * WeakReference} (by default, strong references are used).
226    *
227    * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
228    * candidate for caching.
229    *
230    * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
231    * comparison to determine equality of values. This technically violates the specifications of the
232    * methods {@link Map#containsValue containsValue}, {@link ConcurrentMap#remove(Object, Object)
233    * remove(Object, Object)} and {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V,
234    * V)}, and may not be what you expect.
235    *
236    * @throws IllegalStateException if the value strength was already set
237    * @see WeakReference
238    */
239   @CanIgnoreReturnValue
240   @GwtIncompatible // java.lang.ref.WeakReference
weakValues()241   public MapMaker weakValues() {
242     return setValueStrength(Strength.WEAK);
243   }
244 
245   /**
246    * A dummy singleton value type used by {@link Interners}.
247    *
248    * <p>{@link MapMakerInternalMap} can optimize for memory usage in this case; see {@link
249    * MapMakerInternalMap#createWithDummyValues}.
250    */
251   enum Dummy {
252     VALUE
253   }
254 
setValueStrength(Strength strength)255   MapMaker setValueStrength(Strength strength) {
256     checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
257     valueStrength = checkNotNull(strength);
258     if (strength != Strength.STRONG) {
259       // STRONG could be used during deserialization.
260       useCustomMap = true;
261     }
262     return this;
263   }
264 
getValueStrength()265   Strength getValueStrength() {
266     return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
267   }
268 
269   /**
270    * Builds a thread-safe map. This method does not alter the state of this {@code MapMaker}
271    * instance, so it can be invoked again to create multiple independent maps.
272    *
273    * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
274    * be performed atomically on the returned map. Additionally, {@code size} and {@code
275    * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
276    * writes.
277    *
278    * @return a serializable concurrent map having the requested features
279    */
makeMap()280   public <K, V> ConcurrentMap<K, V> makeMap() {
281     if (!useCustomMap) {
282       return new ConcurrentHashMap<>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
283     }
284     return MapMakerInternalMap.create(this);
285   }
286 
287   /**
288    * Returns a string representation for this MapMaker instance. The exact form of the returned
289    * string is not specified.
290    */
291   @Override
toString()292   public String toString() {
293     MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
294     if (initialCapacity != UNSET_INT) {
295       s.add("initialCapacity", initialCapacity);
296     }
297     if (concurrencyLevel != UNSET_INT) {
298       s.add("concurrencyLevel", concurrencyLevel);
299     }
300     if (keyStrength != null) {
301       s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
302     }
303     if (valueStrength != null) {
304       s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
305     }
306     if (keyEquivalence != null) {
307       s.addValue("keyEquivalence");
308     }
309     return s.toString();
310   }
311 }
312