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