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 * <b>This method is broken.</b> Maps with soft keys offer no functional advantage over maps with 311 * weak keys, and they waste memory by keeping unreachable elements in the map. If your goal is to 312 * create a memory-sensitive map, then consider using soft values instead. 313 * 314 * <p>Specifies that each key (not value) stored in the map should be wrapped in a 315 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will 316 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory 317 * demand. 318 * 319 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 320 * comparison to determine equality of keys, which is a technical violation of the {@link Map} 321 * specification, and may not be what you expect. 322 * 323 * @throws IllegalStateException if the key strength was already set 324 * @see SoftReference 325 * @deprecated use {@link #softValues} to create a memory-sensitive map, or {@link #weakKeys} to 326 * create a map that doesn't hold strong references to the keys. 327 * <b>This method is scheduled for deletion in January 2013.</b> 328 */ 329 @Deprecated 330 @GwtIncompatible("java.lang.ref.SoftReference") 331 @Override 332 public MapMaker softKeys() { 333 return setKeyStrength(Strength.SOFT); 334 } 335 336 MapMaker setKeyStrength(Strength strength) { 337 checkState(keyStrength == null, "Key strength was already set to %s", keyStrength); 338 keyStrength = checkNotNull(strength); 339 if (strength != Strength.STRONG) { 340 // STRONG could be used during deserialization. 341 useCustomMap = true; 342 } 343 return this; 344 } 345 346 Strength getKeyStrength() { 347 return firstNonNull(keyStrength, Strength.STRONG); 348 } 349 350 /** 351 * Specifies that each value (not key) stored in the map should be strongly referenced. 352 * 353 * @throws IllegalStateException if the value strength was already set 354 */ 355 @Override 356 MapMaker strongValues() { 357 return setValueStrength(Strength.STRONG); 358 } 359 360 /** 361 * Specifies that each value (not key) stored in the map should be wrapped in a 362 * {@link WeakReference} (by default, strong references are used). 363 * 364 * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor 365 * candidate for caching; consider {@link #softValues} instead. 366 * 367 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 368 * comparison to determine equality of values. This technically violates the specifications of 369 * the methods {@link Map#containsValue containsValue}, 370 * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and 371 * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you 372 * expect. 373 * 374 * @throws IllegalStateException if the value strength was already set 375 * @see WeakReference 376 */ 377 @GwtIncompatible("java.lang.ref.WeakReference") 378 @Override 379 public MapMaker weakValues() { 380 return setValueStrength(Strength.WEAK); 381 } 382 383 /** 384 * Specifies that each value (not key) stored in the map should be wrapped in a 385 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will 386 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory 387 * demand. 388 * 389 * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain 390 * #maximumSize maximum size} instead of using soft references. You should only use this method if 391 * you are well familiar with the practical consequences of soft references. 392 * 393 * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) 394 * comparison to determine equality of values. This technically violates the specifications of 395 * the methods {@link Map#containsValue containsValue}, 396 * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and 397 * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you 398 * expect. 399 * 400 * @throws IllegalStateException if the value strength was already set 401 * @see SoftReference 402 */ 403 @GwtIncompatible("java.lang.ref.SoftReference") 404 @Override 405 public MapMaker softValues() { 406 return setValueStrength(Strength.SOFT); 407 } 408 409 MapMaker setValueStrength(Strength strength) { 410 checkState(valueStrength == null, "Value strength was already set to %s", valueStrength); 411 valueStrength = checkNotNull(strength); 412 if (strength != Strength.STRONG) { 413 // STRONG could be used during deserialization. 414 useCustomMap = true; 415 } 416 return this; 417 } 418 419 Strength getValueStrength() { 420 return firstNonNull(valueStrength, Strength.STRONG); 421 } 422 423 /** 424 * Old name of {@link #expireAfterWrite}. 425 * 426 * @deprecated Caching functionality in {@code MapMaker} is being moved to 427 * {@link com.google.common.cache.CacheBuilder}. Functionality equivalent to 428 * {@link MapMaker#expiration} is provided by 429 * {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. 430 * <b>This method is scheduled for deletion in July 2012.</b> 431 */ 432 @Deprecated 433 @Override 434 public 435 MapMaker expiration(long duration, TimeUnit unit) { 436 return expireAfterWrite(duration, unit); 437 } 438 439 /** 440 * Specifies that each entry should be automatically removed from the map once a fixed duration 441 * has elapsed after the entry's creation, or the most recent replacement of its value. 442 * 443 * <p>When {@code duration} is zero, elements can be successfully added to the map, but are 444 * evicted immediately. This has a very similar effect to invoking {@link #maximumSize 445 * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without 446 * a code change. 447 * 448 * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or 449 * write operations. Expired entries are currently cleaned up during write operations, or during 450 * occasional read operations in the absense of writes; though this behavior may change in the 451 * future. 452 * 453 * @param duration the length of time after an entry is created that it should be automatically 454 * removed 455 * @param unit the unit that {@code duration} is expressed in 456 * @throws IllegalArgumentException if {@code duration} is negative 457 * @throws IllegalStateException if the time to live or time to idle was already set 458 * @deprecated Caching functionality in {@code MapMaker} is being moved to 459 * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being 460 * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. 461 */ 462 @Deprecated 463 @Override 464 MapMaker expireAfterWrite(long duration, TimeUnit unit) { 465 checkExpiration(duration, unit); 466 this.expireAfterWriteNanos = unit.toNanos(duration); 467 if (duration == 0 && this.nullRemovalCause == null) { 468 // SIZE trumps EXPIRED 469 this.nullRemovalCause = RemovalCause.EXPIRED; 470 } 471 useCustomMap = true; 472 return this; 473 } 474 475 private void checkExpiration(long duration, TimeUnit unit) { 476 checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", 477 expireAfterWriteNanos); 478 checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns", 479 expireAfterAccessNanos); 480 checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); 481 } 482 483 long getExpireAfterWriteNanos() { 484 return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos; 485 } 486 487 /** 488 * Specifies that each entry should be automatically removed from the map once a fixed duration 489 * has elapsed after the entry's last read or write access. 490 * 491 * <p>When {@code duration} is zero, elements can be successfully added to the map, but are 492 * evicted immediately. This has a very similar effect to invoking {@link #maximumSize 493 * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without 494 * a code change. 495 * 496 * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or 497 * write operations. Expired entries are currently cleaned up during write operations, or during 498 * occasional read operations in the absense of writes; though this behavior may change in the 499 * future. 500 * 501 * @param duration the length of time after an entry is last accessed that it should be 502 * automatically removed 503 * @param unit the unit that {@code duration} is expressed in 504 * @throws IllegalArgumentException if {@code duration} is negative 505 * @throws IllegalStateException if the time to idle or time to live was already set 506 * @deprecated Caching functionality in {@code MapMaker} is being moved to 507 * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being 508 * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. 509 */ 510 @Deprecated 511 @GwtIncompatible("To be supported") 512 @Override 513 MapMaker expireAfterAccess(long duration, TimeUnit unit) { 514 checkExpiration(duration, unit); 515 this.expireAfterAccessNanos = unit.toNanos(duration); 516 if (duration == 0 && this.nullRemovalCause == null) { 517 // SIZE trumps EXPIRED 518 this.nullRemovalCause = RemovalCause.EXPIRED; 519 } 520 useCustomMap = true; 521 return this; 522 } 523 524 long getExpireAfterAccessNanos() { 525 return (expireAfterAccessNanos == UNSET_INT) 526 ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos; 527 } 528 529 Ticker getTicker() { 530 return firstNonNull(ticker, Ticker.systemTicker()); 531 } 532 533 /** 534 * Specifies a listener instance, which all maps built using this {@code MapMaker} will notify 535 * each time an entry is removed from the map by any means. 536 * 537 * <p>Each map built by this map maker after this method is called invokes the supplied listener 538 * after removing an element for any reason (see removal causes in {@link RemovalCause}). It will 539 * invoke the listener during invocations of any of that map's public methods (even read-only 540 * methods). 541 * 542 * <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance, 543 * this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original 544 * reference or the returned reference may be used to complete configuration and build the map, 545 * but only the "generic" one is type-safe. That is, it will properly prevent you from building 546 * maps whose key or value types are incompatible with the types accepted by the listener already 547 * provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard 548 * method-chaining idiom, as illustrated in the documentation at top, configuring a {@code 549 * MapMaker} and building your {@link Map} all in a single statement. 550 * 551 * <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map 552 * or cache whose key or value type is incompatible with the listener, you will likely experience 553 * a {@link ClassCastException} at some <i>undefined</i> point in the future. 554 * 555 * @throws IllegalStateException if a removal listener was already set 556 * @deprecated Caching functionality in {@code MapMaker} is being moved to 557 * {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being 558 * replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. 559 */ 560 @Deprecated 561 @GwtIncompatible("To be supported") 562 <K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) { 563 checkState(this.removalListener == null); 564 565 // safely limiting the kinds of maps this can produce 566 @SuppressWarnings("unchecked") 567 GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this; 568 me.removalListener = checkNotNull(listener); 569 useCustomMap = true; 570 return me; 571 } 572 573 /** 574 * Builds a thread-safe map, without on-demand computation of values. This method does not alter 575 * the state of this {@code MapMaker} instance, so it can be invoked again to create multiple 576 * independent maps. 577 * 578 * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to 579 * be performed atomically on the returned map. Additionally, {@code size} and {@code 580 * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent 581 * writes. 582 * 583 * @return a serializable concurrent map having the requested features 584 */ 585 @Override 586 public <K, V> ConcurrentMap<K, V> makeMap() { 587 if (!useCustomMap) { 588 return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel()); 589 } 590 return (nullRemovalCause == null) 591 ? new MapMakerInternalMap<K, V>(this) 592 : new NullConcurrentMap<K, V>(this); 593 } 594 595 /** 596 * Returns a MapMakerInternalMap for the benefit of internal callers that use features of 597 * that class not exposed through ConcurrentMap. 598 */ 599 @Override 600 @GwtIncompatible("MapMakerInternalMap") 601 <K, V> MapMakerInternalMap<K, V> makeCustomMap() { 602 return new MapMakerInternalMap<K, V>(this); 603 } 604 605 /** 606 * Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either 607 * returns an already-computed value for the given key, atomically computes it using the supplied 608 * function, or, if another thread is currently computing the value for this key, simply waits for 609 * that thread to finish and returns its computed value. Note that the function may be executed 610 * concurrently by multiple threads, but only for distinct keys. 611 * 612 * <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports 613 * {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the 614 * {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache 615 * (allowing checked exceptions to be thrown in the process), and more cleanly separates 616 * computation from the cache's {@code Map} view. 617 * 618 * <p>If an entry's value has not finished computing yet, query methods besides {@code get} return 619 * immediately as if an entry doesn't exist. In other words, an entry isn't externally visible 620 * until the value's computation completes. 621 * 622 * <p>{@link Map#get} on the returned map will never return {@code null}. It may throw: 623 * 624 * <ul> 625 * <li>{@link NullPointerException} if the key is null or the computing function returns a null 626 * result 627 * <li>{@link ComputationException} if an exception was thrown by the computing function. If that 628 * exception is already of type {@link ComputationException} it is propagated directly; otherwise 629 * it is wrapped. 630 * </ul> 631 * 632 * <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type 633 * {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at 634 * compile time. Passing an object of a type other than {@code K} can result in that object being 635 * unsafely passed to the computing function as type {@code K}, and unsafely stored in the map. 636 * 637 * <p>If {@link Map#put} is called before a computation completes, other threads waiting on the 638 * computation will wake up and return the stored value. 639 * 640 * <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked 641 * again to create multiple independent maps. 642 * 643 * <p>Insertion, removal, update, and access operations on the returned map safely execute 644 * concurrently by multiple threads. Iterators on the returned map are weakly consistent, 645 * returning elements reflecting the state of the map at some point at or since the creation of 646 * the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed 647 * concurrently with other operations. 648 * 649 * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to 650 * be performed atomically on the returned map. Additionally, {@code size} and {@code 651 * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent 652 * writes. 653 * 654 * @param computingFunction the function used to compute new values 655 * @return a serializable concurrent map having the requested features 656 * @deprecated Caching functionality in {@code MapMaker} is being moved to 657 * {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced 658 * by {@link com.google.common.cache.CacheBuilder#build}. Note that uses of 659 * {@link #makeComputingMap} with {@code AtomicLong} values can often be migrated to 660 * {@link AtomicLongMap}. 661 * <b>This method is scheduled for deletion in February 2013.</b> 662 * 663 */ 664 @Deprecated 665 @Override 666 public <K, V> ConcurrentMap<K, V> makeComputingMap( 667 Function<? super K, ? extends V> computingFunction) { 668 return useNullMap() 669 ? new ComputingMapAdapter<K, V>(this, computingFunction) 670 : new NullComputingConcurrentMap<K, V>(this, computingFunction); 671 } 672 673 /** 674 * Returns a string representation for this MapMaker instance. The exact form of the returned 675 * string is not specificed. 676 */ 677 @Override 678 public String toString() { 679 Objects.ToStringHelper s = Objects.toStringHelper(this); 680 if (initialCapacity != UNSET_INT) { 681 s.add("initialCapacity", initialCapacity); 682 } 683 if (concurrencyLevel != UNSET_INT) { 684 s.add("concurrencyLevel", concurrencyLevel); 685 } 686 if (maximumSize != UNSET_INT) { 687 s.add("maximumSize", maximumSize); 688 } 689 if (expireAfterWriteNanos != UNSET_INT) { 690 s.add("expireAfterWrite", expireAfterWriteNanos + "ns"); 691 } 692 if (expireAfterAccessNanos != UNSET_INT) { 693 s.add("expireAfterAccess", expireAfterAccessNanos + "ns"); 694 } 695 if (keyStrength != null) { 696 s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); 697 } 698 if (valueStrength != null) { 699 s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); 700 } 701 if (keyEquivalence != null) { 702 s.addValue("keyEquivalence"); 703 } 704 if (valueEquivalence != null) { 705 s.addValue("valueEquivalence"); 706 } 707 if (removalListener != null) { 708 s.addValue("removalListener"); 709 } 710 return s.toString(); 711 } 712 713 /** 714 * An object that can receive a notification when an entry is removed from a map. The removal 715 * resulting in notification could have occured to an entry being manually removed or replaced, or 716 * due to eviction resulting from timed expiration, exceeding a maximum size, or garbage 717 * collection. 718 * 719 * <p>An instance may be called concurrently by multiple threads to process different entries. 720 * Implementations of this interface should avoid performing blocking calls or synchronizing on 721 * shared resources. 722 * 723 * @param <K> the most general type of keys this listener can listen for; for 724 * example {@code Object} if any key is acceptable 725 * @param <V> the most general type of values this listener can listen for; for 726 * example {@code Object} if any key is acceptable 727 */ 728 interface RemovalListener<K, V> { 729 /** 730 * Notifies the listener that a removal occurred at some point in the past. 731 */ 732 void onRemoval(RemovalNotification<K, V> notification); 733 } 734 735 /** 736 * A notification of the removal of a single entry. The key or value may be null if it was already 737 * garbage collected. 738 * 739 * <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong 740 * references to the key and value, regardless of the type of references the map may be using. 741 */ 742 static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> { 743 private static final long serialVersionUID = 0; 744 745 private final RemovalCause cause; 746 747 RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) { 748 super(key, value); 749 this.cause = cause; 750 } 751 752 /** 753 * Returns the cause for which the entry was removed. 754 */ 755 public RemovalCause getCause() { 756 return cause; 757 } 758 759 /** 760 * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither 761 * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}). 762 */ 763 public boolean wasEvicted() { 764 return cause.wasEvicted(); 765 } 766 } 767 768 /** 769 * The reason why an entry was removed. 770 */ 771 enum RemovalCause { 772 /** 773 * The entry was manually removed by the user. This can result from the user invoking 774 * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}. 775 */ 776 EXPLICIT { 777 @Override 778 boolean wasEvicted() { 779 return false; 780 } 781 }, 782 783 /** 784 * The entry itself was not actually removed, but its value was replaced by the user. This can 785 * result from the user invoking {@link Map#put}, {@link Map#putAll}, 786 * {@link ConcurrentMap#replace(Object, Object)}, or 787 * {@link ConcurrentMap#replace(Object, Object, Object)}. 788 */ 789 REPLACED { 790 @Override 791 boolean wasEvicted() { 792 return false; 793 } 794 }, 795 796 /** 797 * The entry was removed automatically because its key or value was garbage-collected. This 798 * can occur when using {@link #softKeys}, {@link #softValues}, {@link #weakKeys}, or {@link 799 * #weakValues}. 800 */ 801 COLLECTED { 802 @Override 803 boolean wasEvicted() { 804 return true; 805 } 806 }, 807 808 /** 809 * The entry's expiration timestamp has passed. This can occur when using {@link 810 * #expireAfterWrite} or {@link #expireAfterAccess}. 811 */ 812 EXPIRED { 813 @Override 814 boolean wasEvicted() { 815 return true; 816 } 817 }, 818 819 /** 820 * The entry was evicted due to size constraints. This can occur when using {@link 821 * #maximumSize}. 822 */ 823 SIZE { 824 @Override 825 boolean wasEvicted() { 826 return true; 827 } 828 }; 829 830 /** 831 * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither 832 * {@link #EXPLICIT} nor {@link #REPLACED}). 833 */ 834 abstract boolean wasEvicted(); 835 } 836 837 /** A map that is always empty and evicts on insertion. */ 838 static class NullConcurrentMap<K, V> extends AbstractMap<K, V> 839 implements ConcurrentMap<K, V>, Serializable { 840 private static final long serialVersionUID = 0; 841 842 private final RemovalListener<K, V> removalListener; 843 private final RemovalCause removalCause; 844 845 NullConcurrentMap(MapMaker mapMaker) { 846 removalListener = mapMaker.getRemovalListener(); 847 removalCause = mapMaker.nullRemovalCause; 848 } 849 850 // implements ConcurrentMap 851 852 @Override 853 public boolean containsKey(@Nullable Object key) { 854 return false; 855 } 856 857 @Override 858 public boolean containsValue(@Nullable Object value) { 859 return false; 860 } 861 862 @Override 863 public V get(@Nullable Object key) { 864 return null; 865 } 866 867 void notifyRemoval(K key, V value) { 868 RemovalNotification<K, V> notification = 869 new RemovalNotification<K, V>(key, value, removalCause); 870 removalListener.onRemoval(notification); 871 } 872 873 @Override 874 public V put(K key, V value) { 875 checkNotNull(key); 876 checkNotNull(value); 877 notifyRemoval(key, value); 878 return null; 879 } 880 881 @Override 882 public V putIfAbsent(K key, V value) { 883 return put(key, value); 884 } 885 886 @Override 887 public V remove(@Nullable Object key) { 888 return null; 889 } 890 891 @Override 892 public boolean remove(@Nullable Object key, @Nullable Object value) { 893 return false; 894 } 895 896 @Override 897 public V replace(K key, V value) { 898 checkNotNull(key); 899 checkNotNull(value); 900 return null; 901 } 902 903 @Override 904 public boolean replace(K key, @Nullable V oldValue, V newValue) { 905 checkNotNull(key); 906 checkNotNull(newValue); 907 return false; 908 } 909 910 @Override 911 public Set<Entry<K, V>> entrySet() { 912 return Collections.emptySet(); 913 } 914 } 915 916 /** Computes on retrieval and evicts the result. */ 917 static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> { 918 private static final long serialVersionUID = 0; 919 920 final Function<? super K, ? extends V> computingFunction; 921 922 NullComputingConcurrentMap( 923 MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { 924 super(mapMaker); 925 this.computingFunction = checkNotNull(computingFunction); 926 } 927 928 @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred 929 @Override 930 public V get(Object k) { 931 K key = (K) k; 932 V value = compute(key); 933 checkNotNull(value, computingFunction + " returned null for key " + key + "."); 934 notifyRemoval(key, value); 935 return value; 936 } 937 938 private V compute(K key) { 939 checkNotNull(key); 940 try { 941 return computingFunction.apply(key); 942 } catch (ComputationException e) { 943 throw e; 944 } catch (Throwable t) { 945 throw new ComputationException(t); 946 } 947 } 948 } 949 950 }