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 015 package com.google.common.collect; 016 017 import static com.google.common.base.Objects.firstNonNull; 018 import static com.google.common.base.Preconditions.checkArgument; 019 import static com.google.common.base.Preconditions.checkNotNull; 020 import static com.google.common.base.Preconditions.checkState; 021 022 import com.google.common.annotations.GwtCompatible; 023 import com.google.common.annotations.GwtIncompatible; 024 import com.google.common.base.Ascii; 025 import com.google.common.base.Equivalence; 026 import com.google.common.base.Equivalences; 027 import com.google.common.base.Function; 028 import com.google.common.base.Objects; 029 import com.google.common.base.Ticker; 030 import com.google.common.collect.ComputingConcurrentHashMap.ComputingMapAdapter; 031 import com.google.common.collect.MapMakerInternalMap.Strength; 032 033 import java.io.Serializable; 034 import java.lang.ref.SoftReference; 035 import java.lang.ref.WeakReference; 036 import java.util.AbstractMap; 037 import java.util.Collections; 038 import java.util.ConcurrentModificationException; 039 import java.util.Map; 040 import java.util.Set; 041 import java.util.concurrent.ConcurrentHashMap; 042 import java.util.concurrent.ConcurrentMap; 043 import java.util.concurrent.TimeUnit; 044 045 import javax.annotation.Nullable; 046 047 /** 048 * <p>A builder of {@link ConcurrentMap} instances having any combination of the following features: 049 * 050 * <ul> 051 * <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain 052 * SoftReference soft} references 053 * <li>least-recently-used eviction when a maximum size is exceeded 054 * <li>time-based expiration of entries, measured since last access or last write 055 * <li>notification of evicted (or otherwise removed) entries 056 * <li>on-demand computation of values for keys not already present 057 * </ul> 058 * 059 * <p>Usage example: <pre> {@code 060 * 061 * ConcurrentMap<Key, Graph> graphs = new MapMaker() 062 * .concurrencyLevel(4) 063 * .weakKeys() 064 * .maximumSize(10000) 065 * .expireAfterWrite(10, TimeUnit.MINUTES) 066 * .makeComputingMap( 067 * new Function<Key, Graph>() { 068 * public Graph apply(Key key) { 069 * return createExpensiveGraph(key); 070 * } 071 * });}</pre> 072 * 073 * These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent map 074 * that behaves similarly to a {@link ConcurrentHashMap}. 075 * 076 * <p>The returned map is implemented as a hash table with similar performance characteristics to 077 * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap} 078 * interface. It does not permit null keys or values. 079 * 080 * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals 081 * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} or {@link 082 * #softKeys} was specified, the map uses identity ({@code ==}) comparisons instead for keys. 083 * Likewise, if {@link #weakValues} or {@link #softValues} was specified, the map uses identity 084 * comparisons for values. 085 * 086 * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means 087 * that they are safe for concurrent use, but if other threads modify the map after the iterator is 088 * created, it is undefined which of these changes, if any, are reflected in that iterator. These 089 * iterators never throw {@link ConcurrentModificationException}. 090 * 091 * <p>If soft or weak references were requested, it is possible for a key or value present in the 092 * the map to be reclaimed by the garbage collector. If this happens, the entry automatically 093 * disappears from the map. A partially-reclaimed entry is never exposed to the user. Any {@link 094 * java.util.Map.Entry} instance retrieved from the map's {@linkplain Map#entrySet entry set} is a 095 * snapshot of that entry's state at the time of retrieval; such entries do, however, support {@link 096 * java.util.Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key. 097 * 098 * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all 099 * the configuration properties of the original map. During deserialization, if the original map had 100 * used soft or weak references, the entries are reconstructed as they were, but it's not unlikely 101 * they'll be quickly garbage-collected before they are ever accessed. 102 * 103 * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link 104 * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code 105 * WeakHashMap} uses {@link Object#equals}. 106 * 107 * @author Bob Lee 108 * @author Charles Fry 109 * @author Kevin Bourrillion 110 * @since 2.0 (imported from Google Collections Library) 111 */ 112 @GwtCompatible(emulated = true) 113 public final class MapMaker extends GenericMapMaker<Object, Object> { 114 private static final int DEFAULT_INITIAL_CAPACITY = 16; 115 private static final int DEFAULT_CONCURRENCY_LEVEL = 4; 116 private static final int DEFAULT_EXPIRATION_NANOS = 0; 117 118 static final int UNSET_INT = -1; 119 120 // TODO(kevinb): dispense with this after benchmarking 121 boolean useCustomMap; 122 123 int initialCapacity = UNSET_INT; 124 int concurrencyLevel = UNSET_INT; 125 int maximumSize = UNSET_INT; 126 127 Strength keyStrength; 128 Strength valueStrength; 129 130 long expireAfterWriteNanos = UNSET_INT; 131 long expireAfterAccessNanos = UNSET_INT; 132 133 RemovalCause nullRemovalCause; 134 135 Equivalence<Object> keyEquivalence; 136 Equivalence<Object> valueEquivalence; 137 138 Ticker ticker; 139 140 /** 141 * Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong 142 * values, and no automatic eviction of any kind. 143 */ 144 public MapMaker() {} 145 146 private boolean useNullMap() { 147 return (nullRemovalCause == null); 148 } 149 150 /** 151 * Sets a custom {@code Equivalence} strategy for comparing keys. 152 * 153 * <p>By default, the map uses {@link Equivalences#identity} to determine key equality when 154 * {@link #weakKeys} or {@link #softKeys} is specified, and {@link Equivalences#equals()} 155 * otherwise. 156 */ 157 @GwtIncompatible("To be supported") 158 @Override 159 MapMaker keyEquivalence(Equivalence<Object> equivalence) { 160 checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence); 161 keyEquivalence = checkNotNull(equivalence); 162 this.useCustomMap = true; 163 return this; 164 } 165 166 Equivalence<Object> getKeyEquivalence() { 167 return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence()); 168 } 169 170 /** 171 * Sets a custom {@code Equivalence} strategy for comparing values. 172 * 173 * <p>By default, the map uses {@link Equivalences#identity} to determine value equality when 174 * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalences#equals()} 175 * otherwise. 176 */ 177 @GwtIncompatible("To be supported") 178 @Override 179 MapMaker valueEquivalence(Equivalence<Object> equivalence) { 180 checkState(valueEquivalence == null, 181 "value equivalence was already set to %s", valueEquivalence); 182 this.valueEquivalence = checkNotNull(equivalence); 183 this.useCustomMap = true; 184 return this; 185 } 186 187 Equivalence<Object> getValueEquivalence() { 188 return firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence()); 189 } 190 191 /** 192 * Sets the minimum total size for the internal hash tables. For example, if the initial capacity 193 * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each 194 * having a hash table of size eight. Providing a large enough estimate at construction time 195 * avoids the need for expensive resizing operations later, but setting this value unnecessarily 196 * high wastes memory. 197 * 198 * @throws IllegalArgumentException if {@code initialCapacity} is negative 199 * @throws IllegalStateException if an initial capacity was already set 200 */ 201 @Override 202 public MapMaker initialCapacity(int initialCapacity) { 203 checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s", 204 this.initialCapacity); 205 checkArgument(initialCapacity >= 0); 206 this.initialCapacity = initialCapacity; 207 return this; 208 } 209 210 int getInitialCapacity() { 211 return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity; 212 } 213 214 /** 215 * Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an 216 * entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map 217 * evicts entries that are less likely to be used again. For example, the map may evict an entry 218 * because it hasn't been used recently or very often. 219 * 220 * <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted 221 * immediately. This has the same effect as invoking {@link #expireAfterWrite 222 * expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0, 223 * unit)}. It can be useful in testing, or to disable caching temporarily without a code change. 224 * 225 * <p>Caching functionality in {@code MapMaker} is being moved to 226 * {@link com.google.common.cache.CacheBuilder}. 227 * 228 * @param size the maximum size of the map 229 * @throws IllegalArgumentException if {@code size} is negative 230 * @throws IllegalStateException if a maximum size was already set 231 * @deprecated Caching functionality in {@code MapMaker} is being moved to 232 * {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being 233 * replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. 234 */ 235 @Deprecated 236 @Override 237 MapMaker maximumSize(int size) { 238 checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s", 239 this.maximumSize); 240 checkArgument(size >= 0, "maximum size must not be negative"); 241 this.maximumSize = size; 242 this.useCustomMap = true; 243 if (maximumSize == 0) { 244 // SIZE trumps EXPIRED 245 this.nullRemovalCause = RemovalCause.SIZE; 246 } 247 return this; 248 } 249 250 /** 251 * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The 252 * table is internally partitioned to try to permit the indicated number of concurrent updates 253 * without contention. Because assignment of entries to these partitions is not necessarily 254 * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to 255 * accommodate as many threads as will ever concurrently modify the table. Using a significantly 256 * higher value than you need can waste space and time, and a significantly lower value can lead 257 * to thread contention. But overestimates and underestimates within an order of magnitude do not 258 * usually have much noticeable impact. A value of one permits only one thread to modify the map 259 * at a time, but since read operations can proceed concurrently, this still yields higher 260 * concurrency than full synchronization. Defaults to 4. 261 * 262 * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will 263 * change again in the future. If you care about this value, you should always choose it 264 * explicitly. 265 * 266 * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive 267 * @throws IllegalStateException if a concurrency level was already set 268 */ 269 @Override 270 public MapMaker concurrencyLevel(int concurrencyLevel) { 271 checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", 272 this.concurrencyLevel); 273 checkArgument(concurrencyLevel > 0); 274 this.concurrencyLevel = concurrencyLevel; 275 return this; 276 } 277 278 int getConcurrencyLevel() { 279 return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel; 280 } 281 282 /** 283 * Specifies that each key (not value) stored in the map should be strongly referenced. 284 * 285 * @throws IllegalStateException if the key strength was already set 286 */ 287 @Override 288 MapMaker strongKeys() { 289 return setKeyStrength(Strength.STRONG); 290 } 291 292 /** 293 * Specifies that each key (not value) stored in the map should be wrapped in a {@link 294 * WeakReference} (by default, strong references are used). 295 * 296 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 297 * comparison to determine equality of keys, which is a technical violation of the {@link Map} 298 * specification, and may not be what you expect. 299 * 300 * @throws IllegalStateException if the key strength was already set 301 * @see WeakReference 302 */ 303 @GwtIncompatible("java.lang.ref.WeakReference") 304 @Override 305 public MapMaker weakKeys() { 306 return setKeyStrength(Strength.WEAK); 307 } 308 309 /** 310 * Specifies that each key (not value) stored in the map should be wrapped in a 311 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will 312 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory 313 * demand. 314 * 315 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 316 * comparison to determine equality of keys, which is a technical violation of the {@link Map} 317 * specification, and may not be what you expect. 318 * 319 * @throws IllegalStateException if the key strength was already set 320 * @see SoftReference 321 * @deprecated use {@link #softValues} to create a memory-sensitive map, or {@link #weakKeys} to 322 * create a map that doesn't hold strong references to the keys. 323 * <b>This method is scheduled for deletion in January 2013.</b> 324 */ 325 @Deprecated 326 @GwtIncompatible("java.lang.ref.SoftReference") 327 @Override 328 public MapMaker softKeys() { 329 return setKeyStrength(Strength.SOFT); 330 } 331 332 MapMaker setKeyStrength(Strength strength) { 333 checkState(keyStrength == null, "Key strength was already set to %s", keyStrength); 334 keyStrength = checkNotNull(strength); 335 if (strength != Strength.STRONG) { 336 // STRONG could be used during deserialization. 337 useCustomMap = true; 338 } 339 return this; 340 } 341 342 Strength getKeyStrength() { 343 return firstNonNull(keyStrength, Strength.STRONG); 344 } 345 346 /** 347 * Specifies that each value (not key) stored in the map should be strongly referenced. 348 * 349 * @throws IllegalStateException if the value strength was already set 350 */ 351 @Override 352 MapMaker strongValues() { 353 return setValueStrength(Strength.STRONG); 354 } 355 356 /** 357 * Specifies that each value (not key) stored in the map should be wrapped in a 358 * {@link WeakReference} (by default, strong references are used). 359 * 360 * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor 361 * candidate for caching; consider {@link #softValues} instead. 362 * 363 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 364 * comparison to determine equality of values. This technically violates the specifications of 365 * the methods {@link Map#containsValue containsValue}, 366 * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and 367 * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you 368 * expect. 369 * 370 * @throws IllegalStateException if the value strength was already set 371 * @see WeakReference 372 */ 373 @GwtIncompatible("java.lang.ref.WeakReference") 374 @Override 375 public MapMaker weakValues() { 376 return setValueStrength(Strength.WEAK); 377 } 378 379 /** 380 * Specifies that each value (not key) stored in the map should be wrapped in a 381 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will 382 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory 383 * demand. 384 * 385 * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain 386 * #maximumSize maximum size} instead of using soft references. You should only use this method if 387 * you are well familiar with the practical consequences of soft references. 388 * 389 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 390 * comparison to determine equality of values. This technically violates the specifications of 391 * the methods {@link Map#containsValue containsValue}, 392 * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and 393 * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you 394 * expect. 395 * 396 * @throws IllegalStateException if the value strength was already set 397 * @see SoftReference 398 */ 399 @GwtIncompatible("java.lang.ref.SoftReference") 400 @Override 401 public MapMaker softValues() { 402 return setValueStrength(Strength.SOFT); 403 } 404 405 MapMaker setValueStrength(Strength strength) { 406 checkState(valueStrength == null, "Value strength was already set to %s", valueStrength); 407 valueStrength = checkNotNull(strength); 408 if (strength != Strength.STRONG) { 409 // STRONG could be used during deserialization. 410 useCustomMap = true; 411 } 412 return this; 413 } 414 415 Strength getValueStrength() { 416 return firstNonNull(valueStrength, Strength.STRONG); 417 } 418 419 /** 420 * Old name of {@link #expireAfterWrite}. 421 * 422 * @deprecated Caching functionality in {@code MapMaker} is being moved to 423 * {@link com.google.common.cache.CacheBuilder}. Functionality equivalent to 424 * {@link MapMaker#expiration} is provided by 425 * {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. 426 * <b>This method is scheduled for deletion in July 2012.</b> 427 */ 428 @Deprecated 429 @Override 430 public 431 MapMaker expiration(long duration, TimeUnit unit) { 432 return expireAfterWrite(duration, unit); 433 } 434 435 /** 436 * Specifies that each entry should be automatically removed from the map once a fixed duration 437 * has elapsed after the entry's creation, or the most recent replacement of its value. 438 * 439 * <p>When {@code duration} is zero, elements can be successfully added to the map, but are 440 * evicted immediately. This has a very similar effect to invoking {@link #maximumSize 441 * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without 442 * a code change. 443 * 444 * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or 445 * write operations. Expired entries are currently cleaned up during write operations, or during 446 * occasional read operations in the absense of writes; though this behavior may change in the 447 * future. 448 * 449 * @param duration the length of time after an entry is created that it should be automatically 450 * removed 451 * @param unit the unit that {@code duration} is expressed in 452 * @throws IllegalArgumentException if {@code duration} is negative 453 * @throws IllegalStateException if the time to live or time to idle was already set 454 * @deprecated Caching functionality in {@code MapMaker} is being moved to 455 * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being 456 * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. 457 */ 458 @Deprecated 459 @Override 460 MapMaker expireAfterWrite(long duration, TimeUnit unit) { 461 checkExpiration(duration, unit); 462 this.expireAfterWriteNanos = unit.toNanos(duration); 463 if (duration == 0 && this.nullRemovalCause == null) { 464 // SIZE trumps EXPIRED 465 this.nullRemovalCause = RemovalCause.EXPIRED; 466 } 467 useCustomMap = true; 468 return this; 469 } 470 471 private void checkExpiration(long duration, TimeUnit unit) { 472 checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", 473 expireAfterWriteNanos); 474 checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns", 475 expireAfterAccessNanos); 476 checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); 477 } 478 479 long getExpireAfterWriteNanos() { 480 return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos; 481 } 482 483 /** 484 * Specifies that each entry should be automatically removed from the map once a fixed duration 485 * has elapsed after the entry's last read or write access. 486 * 487 * <p>When {@code duration} is zero, elements can be successfully added to the map, but are 488 * evicted immediately. This has a very similar effect to invoking {@link #maximumSize 489 * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without 490 * a code change. 491 * 492 * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or 493 * write operations. Expired entries are currently cleaned up during write operations, or during 494 * occasional read operations in the absense of writes; though this behavior may change in the 495 * future. 496 * 497 * @param duration the length of time after an entry is last accessed that it should be 498 * automatically removed 499 * @param unit the unit that {@code duration} is expressed in 500 * @throws IllegalArgumentException if {@code duration} is negative 501 * @throws IllegalStateException if the time to idle or time to live was already set 502 * @deprecated Caching functionality in {@code MapMaker} is being moved to 503 * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being 504 * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. 505 */ 506 @Deprecated 507 @GwtIncompatible("To be supported") 508 @Override 509 MapMaker expireAfterAccess(long duration, TimeUnit unit) { 510 checkExpiration(duration, unit); 511 this.expireAfterAccessNanos = unit.toNanos(duration); 512 if (duration == 0 && this.nullRemovalCause == null) { 513 // SIZE trumps EXPIRED 514 this.nullRemovalCause = RemovalCause.EXPIRED; 515 } 516 useCustomMap = true; 517 return this; 518 } 519 520 long getExpireAfterAccessNanos() { 521 return (expireAfterAccessNanos == UNSET_INT) 522 ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos; 523 } 524 525 Ticker getTicker() { 526 return firstNonNull(ticker, Ticker.systemTicker()); 527 } 528 529 /** 530 * Specifies a listener instance, which all maps built using this {@code MapMaker} will notify 531 * each time an entry is removed from the map by any means. 532 * 533 * <p>Each map built by this map maker after this method is called invokes the supplied listener 534 * after removing an element for any reason (see removal causes in {@link RemovalCause}). It will 535 * invoke the listener during invocations of any of that map's public methods (even read-only 536 * methods). 537 * 538 * <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance, 539 * this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original 540 * reference or the returned reference may be used to complete configuration and build the map, 541 * but only the "generic" one is type-safe. That is, it will properly prevent you from building 542 * maps whose key or value types are incompatible with the types accepted by the listener already 543 * provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard 544 * method-chaining idiom, as illustrated in the documentation at top, configuring a {@code 545 * MapMaker} and building your {@link Map} all in a single statement. 546 * 547 * <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map 548 * or cache whose key or value type is incompatible with the listener, you will likely experience 549 * a {@link ClassCastException} at some <i>undefined</i> point in the future. 550 * 551 * @throws IllegalStateException if a removal listener was already set 552 * @deprecated Caching functionality in {@code MapMaker} is being moved to 553 * {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being 554 * replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. 555 */ 556 @Deprecated 557 @GwtIncompatible("To be supported") 558 <K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) { 559 checkState(this.removalListener == null); 560 561 // safely limiting the kinds of maps this can produce 562 @SuppressWarnings("unchecked") 563 GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this; 564 me.removalListener = checkNotNull(listener); 565 useCustomMap = true; 566 return me; 567 } 568 569 /** 570 * Builds a thread-safe map, without on-demand computation of values. This method does not alter 571 * the state of this {@code MapMaker} instance, so it can be invoked again to create multiple 572 * independent maps. 573 * 574 * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to 575 * be performed atomically on the returned map. Additionally, {@code size} and {@code 576 * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent 577 * writes. 578 * 579 * @return a serializable concurrent map having the requested features 580 */ 581 @Override 582 public <K, V> ConcurrentMap<K, V> makeMap() { 583 if (!useCustomMap) { 584 return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel()); 585 } 586 return (nullRemovalCause == null) 587 ? new MapMakerInternalMap<K, V>(this) 588 : new NullConcurrentMap<K, V>(this); 589 } 590 591 /** 592 * Returns a MapMakerInternalMap for the benefit of internal callers that use features of 593 * that class not exposed through ConcurrentMap. 594 */ 595 @Override 596 @GwtIncompatible("MapMakerInternalMap") 597 <K, V> MapMakerInternalMap<K, V> makeCustomMap() { 598 return new MapMakerInternalMap<K, V>(this); 599 } 600 601 /** 602 * Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either 603 * returns an already-computed value for the given key, atomically computes it using the supplied 604 * function, or, if another thread is currently computing the value for this key, simply waits for 605 * that thread to finish and returns its computed value. Note that the function may be executed 606 * concurrently by multiple threads, but only for distinct keys. 607 * 608 * <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports 609 * {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the 610 * {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache 611 * (allowing checked exceptions to be thrown in the process), and more cleanly separates 612 * computation from the cache's {@code Map} view. 613 * 614 * <p>If an entry's value has not finished computing yet, query methods besides {@code get} return 615 * immediately as if an entry doesn't exist. In other words, an entry isn't externally visible 616 * until the value's computation completes. 617 * 618 * <p>{@link Map#get} on the returned map will never return {@code null}. It may throw: 619 * 620 * <ul> 621 * <li>{@link NullPointerException} if the key is null or the computing function returns a null 622 * result 623 * <li>{@link ComputationException} if an exception was thrown by the computing function. If that 624 * exception is already of type {@link ComputationException} it is propagated directly; otherwise 625 * it is wrapped. 626 * </ul> 627 * 628 * <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type 629 * {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at 630 * compile time. Passing an object of a type other than {@code K} can result in that object being 631 * unsafely passed to the computing function as type {@code K}, and unsafely stored in the map. 632 * 633 * <p>If {@link Map#put} is called before a computation completes, other threads waiting on the 634 * computation will wake up and return the stored value. 635 * 636 * <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked 637 * again to create multiple independent maps. 638 * 639 * <p>Insertion, removal, update, and access operations on the returned map safely execute 640 * concurrently by multiple threads. Iterators on the returned map are weakly consistent, 641 * returning elements reflecting the state of the map at some point at or since the creation of 642 * the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed 643 * concurrently with other operations. 644 * 645 * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to 646 * be performed atomically on the returned map. Additionally, {@code size} and {@code 647 * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent 648 * writes. 649 * 650 * @param computingFunction the function used to compute new values 651 * @return a serializable concurrent map having the requested features 652 * @deprecated Caching functionality in {@code MapMaker} is being moved to 653 * {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced 654 * by {@link com.google.common.cache.CacheBuilder#build}. Note that uses of 655 * {@link #makeComputingMap} with {@code AtomicLong} values can often be migrated to 656 * {@link AtomicLongMap}. 657 * <b>This method is scheduled for deletion in February 2013.</b> 658 * 659 */ 660 @Deprecated 661 @Override 662 public <K, V> ConcurrentMap<K, V> makeComputingMap( 663 Function<? super K, ? extends V> computingFunction) { 664 return useNullMap() 665 ? new ComputingMapAdapter<K, V>(this, computingFunction) 666 : new NullComputingConcurrentMap<K, V>(this, computingFunction); 667 } 668 669 /** 670 * Returns a string representation for this MapMaker instance. The exact form of the returned 671 * string is not specificed. 672 */ 673 @Override 674 public String toString() { 675 Objects.ToStringHelper s = Objects.toStringHelper(this); 676 if (initialCapacity != UNSET_INT) { 677 s.add("initialCapacity", initialCapacity); 678 } 679 if (concurrencyLevel != UNSET_INT) { 680 s.add("concurrencyLevel", concurrencyLevel); 681 } 682 if (maximumSize != UNSET_INT) { 683 s.add("maximumSize", maximumSize); 684 } 685 if (expireAfterWriteNanos != UNSET_INT) { 686 s.add("expireAfterWrite", expireAfterWriteNanos + "ns"); 687 } 688 if (expireAfterAccessNanos != UNSET_INT) { 689 s.add("expireAfterAccess", expireAfterAccessNanos + "ns"); 690 } 691 if (keyStrength != null) { 692 s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); 693 } 694 if (valueStrength != null) { 695 s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); 696 } 697 if (keyEquivalence != null) { 698 s.addValue("keyEquivalence"); 699 } 700 if (valueEquivalence != null) { 701 s.addValue("valueEquivalence"); 702 } 703 if (removalListener != null) { 704 s.addValue("removalListener"); 705 } 706 return s.toString(); 707 } 708 709 /** 710 * An object that can receive a notification when an entry is removed from a map. The removal 711 * resulting in notification could have occured to an entry being manually removed or replaced, or 712 * due to eviction resulting from timed expiration, exceeding a maximum size, or garbage 713 * collection. 714 * 715 * <p>An instance may be called concurrently by multiple threads to process different entries. 716 * Implementations of this interface should avoid performing blocking calls or synchronizing on 717 * shared resources. 718 * 719 * @param <K> the most general type of keys this listener can listen for; for 720 * example {@code Object} if any key is acceptable 721 * @param <V> the most general type of values this listener can listen for; for 722 * example {@code Object} if any key is acceptable 723 */ 724 interface RemovalListener<K, V> { 725 /** 726 * Notifies the listener that a removal occurred at some point in the past. 727 */ 728 void onRemoval(RemovalNotification<K, V> notification); 729 } 730 731 /** 732 * A notification of the removal of a single entry. The key or value may be null if it was already 733 * garbage collected. 734 * 735 * <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong 736 * references to the key and value, regardless of the type of references the map may be using. 737 */ 738 static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> { 739 private static final long serialVersionUID = 0; 740 741 private final RemovalCause cause; 742 743 RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) { 744 super(key, value); 745 this.cause = cause; 746 } 747 748 /** 749 * Returns the cause for which the entry was removed. 750 */ 751 public RemovalCause getCause() { 752 return cause; 753 } 754 755 /** 756 * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither 757 * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}). 758 */ 759 public boolean wasEvicted() { 760 return cause.wasEvicted(); 761 } 762 } 763 764 /** 765 * The reason why an entry was removed. 766 */ 767 enum RemovalCause { 768 /** 769 * The entry was manually removed by the user. This can result from the user invoking 770 * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}. 771 */ 772 EXPLICIT { 773 @Override 774 boolean wasEvicted() { 775 return false; 776 } 777 }, 778 779 /** 780 * The entry itself was not actually removed, but its value was replaced by the user. This can 781 * result from the user invoking {@link Map#put}, {@link Map#putAll}, 782 * {@link ConcurrentMap#replace(Object, Object)}, or 783 * {@link ConcurrentMap#replace(Object, Object, Object)}. 784 */ 785 REPLACED { 786 @Override 787 boolean wasEvicted() { 788 return false; 789 } 790 }, 791 792 /** 793 * The entry was removed automatically because its key or value was garbage-collected. This 794 * can occur when using {@link #softKeys}, {@link #softValues}, {@link #weakKeys}, or {@link 795 * #weakValues}. 796 */ 797 COLLECTED { 798 @Override 799 boolean wasEvicted() { 800 return true; 801 } 802 }, 803 804 /** 805 * The entry's expiration timestamp has passed. This can occur when using {@link 806 * #expireAfterWrite} or {@link #expireAfterAccess}. 807 */ 808 EXPIRED { 809 @Override 810 boolean wasEvicted() { 811 return true; 812 } 813 }, 814 815 /** 816 * The entry was evicted due to size constraints. This can occur when using {@link 817 * #maximumSize}. 818 */ 819 SIZE { 820 @Override 821 boolean wasEvicted() { 822 return true; 823 } 824 }; 825 826 /** 827 * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither 828 * {@link #EXPLICIT} nor {@link #REPLACED}). 829 */ 830 abstract boolean wasEvicted(); 831 } 832 833 /** A map that is always empty and evicts on insertion. */ 834 static class NullConcurrentMap<K, V> extends AbstractMap<K, V> 835 implements ConcurrentMap<K, V>, Serializable { 836 private static final long serialVersionUID = 0; 837 838 private final RemovalListener<K, V> removalListener; 839 private final RemovalCause removalCause; 840 841 NullConcurrentMap(MapMaker mapMaker) { 842 removalListener = mapMaker.getRemovalListener(); 843 removalCause = mapMaker.nullRemovalCause; 844 } 845 846 // implements ConcurrentMap 847 848 @Override 849 public boolean containsKey(@Nullable Object key) { 850 return false; 851 } 852 853 @Override 854 public boolean containsValue(@Nullable Object value) { 855 return false; 856 } 857 858 @Override 859 public V get(@Nullable Object key) { 860 return null; 861 } 862 863 void notifyRemoval(K key, V value) { 864 RemovalNotification<K, V> notification = 865 new RemovalNotification<K, V>(key, value, removalCause); 866 removalListener.onRemoval(notification); 867 } 868 869 @Override 870 public V put(K key, V value) { 871 checkNotNull(key); 872 checkNotNull(value); 873 notifyRemoval(key, value); 874 return null; 875 } 876 877 @Override 878 public V putIfAbsent(K key, V value) { 879 return put(key, value); 880 } 881 882 @Override 883 public V remove(@Nullable Object key) { 884 return null; 885 } 886 887 @Override 888 public boolean remove(@Nullable Object key, @Nullable Object value) { 889 return false; 890 } 891 892 @Override 893 public V replace(K key, V value) { 894 checkNotNull(key); 895 checkNotNull(value); 896 return null; 897 } 898 899 @Override 900 public boolean replace(K key, @Nullable V oldValue, V newValue) { 901 checkNotNull(key); 902 checkNotNull(newValue); 903 return false; 904 } 905 906 @Override 907 public Set<Entry<K, V>> entrySet() { 908 return Collections.emptySet(); 909 } 910 } 911 912 /** Computes on retrieval and evicts the result. */ 913 static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> { 914 private static final long serialVersionUID = 0; 915 916 final Function<? super K, ? extends V> computingFunction; 917 918 NullComputingConcurrentMap( 919 MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { 920 super(mapMaker); 921 this.computingFunction = checkNotNull(computingFunction); 922 } 923 924 @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred 925 @Override 926 public V get(Object k) { 927 K key = (K) k; 928 V value = compute(key); 929 checkNotNull(value, computingFunction + " returned null for key " + key + "."); 930 notifyRemoval(key, value); 931 return value; 932 } 933 934 private V compute(K key) { 935 checkNotNull(key); 936 try { 937 return computingFunction.apply(key); 938 } catch (ComputationException e) { 939 throw e; 940 } catch (Throwable t) { 941 throw new ComputationException(t); 942 } 943 } 944 } 945 946 }