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; 033import javax.annotation.CheckForNull; 034 035/** 036 * A builder of {@link ConcurrentMap} instances that can have keys or values automatically wrapped 037 * in {@linkplain WeakReference weak} references. 038 * 039 * <p>Usage example: 040 * 041 * <pre>{@code 042 * ConcurrentMap<Request, Stopwatch> timers = new MapMaker() 043 * .concurrencyLevel(4) 044 * .weakKeys() 045 * .makeMap(); 046 * }</pre> 047 * 048 * <p>These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent 049 * map that behaves similarly to a {@link ConcurrentHashMap}. 050 * 051 * <p>The returned map is implemented as a hash table with similar performance characteristics to 052 * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap} 053 * interface. It does not permit null keys or values. 054 * 055 * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals 056 * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was 057 * specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link 058 * #weakValues} was specified, the map uses identity comparisons for values. 059 * 060 * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means 061 * that they are safe for concurrent use, but if other threads modify the map after the iterator is 062 * created, it is undefined which of these changes, if any, are reflected in that iterator. These 063 * iterators never throw {@link ConcurrentModificationException}. 064 * 065 * <p>If {@link #weakKeys} or {@link #weakValues} are requested, it is possible for a key or value 066 * present in the map to be reclaimed by the garbage collector. Entries with reclaimed keys or 067 * values may be removed from the map on each map modification or on occasional map accesses; such 068 * entries may be counted by {@link Map#size}, but will never be visible to read or write 069 * operations. A partially-reclaimed entry is never exposed to the user. Any {@link Map.Entry} 070 * instance retrieved from the map's {@linkplain Map#entrySet entry set} is a snapshot of that 071 * entry's state at the time of retrieval; such entries do, however, support {@link 072 * Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key. 073 * 074 * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all 075 * the configuration properties of the original map. During deserialization, if the original map had 076 * used weak references, the entries are reconstructed as they were, but it's not unlikely they'll 077 * be quickly garbage-collected before they are ever accessed. 078 * 079 * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link 080 * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code 081 * WeakHashMap} uses {@link Object#equals}. 082 * 083 * @author Bob Lee 084 * @author Charles Fry 085 * @author Kevin Bourrillion 086 * @since 2.0 087 */ 088@GwtCompatible(emulated = true) 089@ElementTypesAreNonnullByDefault 090public final class MapMaker { 091 private static final int DEFAULT_INITIAL_CAPACITY = 16; 092 private static final int DEFAULT_CONCURRENCY_LEVEL = 4; 093 094 static final int UNSET_INT = -1; 095 096 // TODO(kevinb): dispense with this after benchmarking 097 boolean useCustomMap; 098 099 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 */ 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 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 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 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 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 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 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 205 public MapMaker weakKeys() { 206 return setKeyStrength(Strength.WEAK); 207 } 208 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 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 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 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 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 */ 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 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}