001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.base.Ascii;
024import com.google.common.base.Equivalence;
025import com.google.common.base.MoreObjects;
026import com.google.common.collect.MapMakerInternalMap.Strength;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import java.lang.ref.WeakReference;
029import java.util.ConcurrentModificationException;
030import java.util.Map;
031import java.util.concurrent.ConcurrentHashMap;
032import java.util.concurrent.ConcurrentMap;
033
034/**
035 * A builder of {@link ConcurrentMap} instances that can have keys or values automatically wrapped
036 * in {@linkplain WeakReference weak} references.
037 *
038 * <p>Usage example:
039 *
040 * <pre>{@code
041 * ConcurrentMap<Request, Stopwatch> timers = new MapMaker()
042 *     .concurrencyLevel(4)
043 *     .weakKeys()
044 *     .makeMap();
045 * }</pre>
046 *
047 * <p>These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent
048 * map that behaves similarly to a {@link ConcurrentHashMap}.
049 *
050 * <p>The returned map is implemented as a hash table with similar performance characteristics to
051 * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap}
052 * interface. It does not permit null keys or values.
053 *
054 * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals
055 * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was
056 * specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link
057 * #weakValues} was specified, the map uses identity comparisons for values.
058 *
059 * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means
060 * that they are safe for concurrent use, but if other threads modify the map after the iterator is
061 * created, it is undefined which of these changes, if any, are reflected in that iterator. These
062 * iterators never throw {@link ConcurrentModificationException}.
063 *
064 * <p>If {@link #weakKeys} or {@link #weakValues} are requested, it is possible for a key or value
065 * present in the map to be reclaimed by the garbage collector. Entries with reclaimed keys or
066 * values may be removed from the map on each map modification or on occasional map accesses; such
067 * entries may be counted by {@link Map#size}, but will never be visible to read or write
068 * operations. A partially-reclaimed entry is never exposed to the user. Any {@link java.util.Entry}
069 * instance retrieved from the map's {@linkplain Map#entrySet entry set} is a snapshot of that
070 * entry's state at the time of retrieval; such entries do, however, support {@link
071 * java.util.Entry#setValue}, which simply calls {@link Map#put} on the entry's key.
072 *
073 * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all
074 * the configuration properties of the original map. During deserialization, if the original map had
075 * used weak references, the entries are reconstructed as they were, but it's not unlikely they'll
076 * be quickly garbage-collected before they are ever accessed.
077 *
078 * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link
079 * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code
080 * WeakHashMap} uses {@link Object#equals}.
081 *
082 * @author Bob Lee
083 * @author Charles Fry
084 * @author Kevin Bourrillion
085 * @since 2.0
086 */
087@GwtCompatible(emulated = true)
088public final class MapMaker {
089  private static final int DEFAULT_INITIAL_CAPACITY = 16;
090  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
091
092  static final int UNSET_INT = -1;
093
094  // TODO(kevinb): dispense with this after benchmarking
095  boolean useCustomMap;
096
097  int initialCapacity = UNSET_INT;
098  int concurrencyLevel = UNSET_INT;
099
100  Strength keyStrength;
101  Strength valueStrength;
102
103  Equivalence<Object> keyEquivalence;
104
105  /**
106   * Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong
107   * values, and no automatic eviction of any kind.
108   */
109  public MapMaker() {}
110
111  /**
112   * Sets a custom {@code Equivalence} strategy for comparing keys.
113   *
114   * <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link
115   * #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is
116   * used is in {@link Interners.WeakInterner}.
117   */
118  @CanIgnoreReturnValue
119  @GwtIncompatible // To be supported
120  MapMaker keyEquivalence(Equivalence<Object> equivalence) {
121    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
122    keyEquivalence = checkNotNull(equivalence);
123    this.useCustomMap = true;
124    return this;
125  }
126
127  Equivalence<Object> getKeyEquivalence() {
128    return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
129  }
130
131  /**
132   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
133   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
134   * having a hash table of size eight. Providing a large enough estimate at construction time
135   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
136   * high wastes memory.
137   *
138   * @throws IllegalArgumentException if {@code initialCapacity} is negative
139   * @throws IllegalStateException if an initial capacity was already set
140   */
141  @CanIgnoreReturnValue
142  public MapMaker initialCapacity(int initialCapacity) {
143    checkState(
144        this.initialCapacity == UNSET_INT,
145        "initial capacity was already set to %s",
146        this.initialCapacity);
147    checkArgument(initialCapacity >= 0);
148    this.initialCapacity = initialCapacity;
149    return this;
150  }
151
152  int getInitialCapacity() {
153    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
154  }
155
156  /**
157   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
158   * table is internally partitioned to try to permit the indicated number of concurrent updates
159   * without contention. Because assignment of entries to these partitions is not necessarily
160   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
161   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
162   * higher value than you need can waste space and time, and a significantly lower value can lead
163   * to thread contention. But overestimates and underestimates within an order of magnitude do not
164   * usually have much noticeable impact. A value of one permits only one thread to modify the map
165   * at a time, but since read operations can proceed concurrently, this still yields higher
166   * concurrency than full synchronization. Defaults to 4.
167   *
168   * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
169   * change again in the future. If you care about this value, you should always choose it
170   * explicitly.
171   *
172   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
173   * @throws IllegalStateException if a concurrency level was already set
174   */
175  @CanIgnoreReturnValue
176  public MapMaker concurrencyLevel(int concurrencyLevel) {
177    checkState(
178        this.concurrencyLevel == UNSET_INT,
179        "concurrency level was already set to %s",
180        this.concurrencyLevel);
181    checkArgument(concurrencyLevel > 0);
182    this.concurrencyLevel = concurrencyLevel;
183    return this;
184  }
185
186  int getConcurrencyLevel() {
187    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
188  }
189
190  /**
191   * Specifies that each key (not value) stored in the map should be wrapped in a {@link
192   * WeakReference} (by default, strong references are used).
193   *
194   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
195   * comparison to determine equality of keys, which is a technical violation of the {@link Map}
196   * specification, and may not be what you expect.
197   *
198   * @throws IllegalStateException if the key strength was already set
199   * @see WeakReference
200   */
201  @CanIgnoreReturnValue
202  @GwtIncompatible // java.lang.ref.WeakReference
203  public MapMaker weakKeys() {
204    return setKeyStrength(Strength.WEAK);
205  }
206
207  MapMaker setKeyStrength(Strength strength) {
208    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
209    keyStrength = checkNotNull(strength);
210    if (strength != Strength.STRONG) {
211      // STRONG could be used during deserialization.
212      useCustomMap = true;
213    }
214    return this;
215  }
216
217  Strength getKeyStrength() {
218    return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
219  }
220
221  /**
222   * Specifies that each value (not key) stored in the map should be wrapped in a {@link
223   * WeakReference} (by default, strong references are used).
224   *
225   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
226   * candidate for caching.
227   *
228   * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
229   * comparison to determine equality of values. This technically violates the specifications of the
230   * methods {@link Map#containsValue containsValue}, {@link ConcurrentMap#remove(Object, Object)
231   * remove(Object, Object)} and {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V,
232   * V)}, and may not be what you expect.
233   *
234   * @throws IllegalStateException if the value strength was already set
235   * @see WeakReference
236   */
237  @CanIgnoreReturnValue
238  @GwtIncompatible // java.lang.ref.WeakReference
239  public MapMaker weakValues() {
240    return setValueStrength(Strength.WEAK);
241  }
242
243  /**
244   * A dummy singleton value type used by {@link Interners}.
245   *
246   * <p>{@link MapMakerInternalMap} can optimize for memory usage in this case; see {@link
247   * MapMakerInternalMap#createWithDummyValues}.
248   */
249  enum Dummy {
250    VALUE
251  }
252
253  MapMaker setValueStrength(Strength strength) {
254    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
255    valueStrength = checkNotNull(strength);
256    if (strength != Strength.STRONG) {
257      // STRONG could be used during deserialization.
258      useCustomMap = true;
259    }
260    return this;
261  }
262
263  Strength getValueStrength() {
264    return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
265  }
266
267  /**
268   * Builds a thread-safe map. This method does not alter the state of this {@code MapMaker}
269   * instance, so it can be invoked again to create multiple independent maps.
270   *
271   * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
272   * be performed atomically on the returned map. Additionally, {@code size} and {@code
273   * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
274   * writes.
275   *
276   * @return a serializable concurrent map having the requested features
277   */
278  public <K, V> ConcurrentMap<K, V> makeMap() {
279    if (!useCustomMap) {
280      return new ConcurrentHashMap<>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
281    }
282    return MapMakerInternalMap.create(this);
283  }
284
285  /**
286   * Returns a string representation for this MapMaker instance. The exact form of the returned
287   * string is not specified.
288   */
289  @Override
290  public String toString() {
291    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
292    if (initialCapacity != UNSET_INT) {
293      s.add("initialCapacity", initialCapacity);
294    }
295    if (concurrencyLevel != UNSET_INT) {
296      s.add("concurrencyLevel", concurrencyLevel);
297    }
298    if (keyStrength != null) {
299      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
300    }
301    if (valueStrength != null) {
302      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
303    }
304    if (keyEquivalence != null) {
305      s.addValue("keyEquivalence");
306    }
307    return s.toString();
308  }
309}