diff --git a/android/guava/src/com/google/common/cache/CacheBuilder.java b/android/guava/src/com/google/common/cache/CacheBuilder.java index b690973b2505..d16023fac8ee 100644 --- a/android/guava/src/com/google/common/cache/CacheBuilder.java +++ b/android/guava/src/com/google/common/cache/CacheBuilder.java @@ -97,7 +97,7 @@ *
  • accumulation of cache access statistics * * - *

    These features are all optional; caches can be created using all or none of them. By default + *

    These features are all optional; caches can be created using all or none of them. By default, * cache instances created by {@code CacheBuilder} will not perform any type of eviction. * *

    Usage example: @@ -231,13 +231,16 @@ public CacheStats snapshot() { }); static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0); - static final Supplier CACHE_STATS_COUNTER = - new Supplier() { - @Override - public StatsCounter get() { - return new SimpleStatsCounter(); - } - }; + /* + * We avoid using a method reference here for now: Inside Google, CacheBuilder is used from the + * implementation of a custom ClassLoader that is sometimes used as a system classloader. That's a + * problem because method-reference linking tries to look up the system classloader, and it fails + * because there isn't one yet. + * + * I would have guessed that a lambda would produce the same problem, but maybe it's safe because + * the lambda implementation is generated as a method in the _same class_ as the usage? + */ + static final Supplier CACHE_STATS_COUNTER = () -> new SimpleStatsCounter(); enum NullListener implements RemovalListener { INSTANCE; @@ -825,11 +828,11 @@ Ticker getTicker(boolean recordsTime) { * *

    Warning: after invoking this method, do not continue to use this cache builder * reference; instead use the reference this method returns. At runtime, these point to the - * same instance, but only the returned reference has the correct generic type information so as - * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in - * the class documentation above, configuring a builder and building your cache in a single - * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown - * by a cache operation at some undefined point in the future. + * same instance, but only the returned reference has the correct generic type information to + * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the + * class documentation above, configuring a builder and building your cache in a single statement. + * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache + * operation at some undefined point in the future. * *

    Warning: any exception thrown by {@code listener} will not be propagated to * the {@code Cache} user, only logged via a {@link Logger}. diff --git a/android/guava/src/com/google/common/cache/CacheLoader.java b/android/guava/src/com/google/common/cache/CacheLoader.java index bb544cdcdc01..9e9ca3f979fb 100644 --- a/android/guava/src/com/google/common/cache/CacheLoader.java +++ b/android/guava/src/com/google/common/cache/CacheLoader.java @@ -26,7 +26,6 @@ import com.google.errorprone.annotations.CheckReturnValue; import java.io.Serializable; import java.util.Map; -import java.util.concurrent.Callable; import java.util.concurrent.Executor; /** @@ -154,7 +153,7 @@ public static CacheLoader from(Function function) { */ @CheckReturnValue public static CacheLoader from(Supplier supplier) { - return new SupplierToCacheLoader(supplier); + return new SupplierToCacheLoader<>(supplier); } private static final class FunctionToCacheLoader extends CacheLoader @@ -195,15 +194,9 @@ public V load(K key) throws Exception { } @Override - public ListenableFuture reload(final K key, final V oldValue) throws Exception { + public ListenableFuture reload(final K key, final V oldValue) { ListenableFutureTask task = - ListenableFutureTask.create( - new Callable() { - @Override - public V call() throws Exception { - return loader.reload(key, oldValue).get(); - } - }); + ListenableFutureTask.create(() -> loader.reload(key, oldValue).get()); executor.execute(task); return task; } diff --git a/android/guava/src/com/google/common/cache/CacheStats.java b/android/guava/src/com/google/common/cache/CacheStats.java index bf489e419d3e..7399adf23f40 100644 --- a/android/guava/src/com/google/common/cache/CacheStats.java +++ b/android/guava/src/com/google/common/cache/CacheStats.java @@ -152,8 +152,8 @@ public double missRate() { /** * Returns the total number of times that {@link Cache} lookup methods attempted to load new - * values. This includes both successful load operations, as well as those that threw exceptions. - * This is defined as {@code loadSuccessCount + loadExceptionCount}. + * values. This includes both successful load operations and those that threw exceptions. This is + * defined as {@code loadSuccessCount + loadExceptionCount}. * *

    Note: the values of the metrics are undefined in case of overflow (though it is * guaranteed not to throw an exception). If you require specific handling, we recommend diff --git a/android/guava/src/com/google/common/cache/LocalCache.java b/android/guava/src/com/google/common/cache/LocalCache.java index f3744e59cbff..7cf7b5a6a3a8 100644 --- a/android/guava/src/com/google/common/cache/LocalCache.java +++ b/android/guava/src/com/google/common/cache/LocalCache.java @@ -28,7 +28,6 @@ import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Equivalence; -import com.google.common.base.Function; import com.google.common.base.Stopwatch; import com.google.common.base.Ticker; import com.google.common.cache.AbstractCache.SimpleStatsCounter; @@ -256,8 +255,8 @@ class LocalCache extends AbstractMap implements ConcurrentMap removalListener = builder.getRemovalListener(); removalNotificationQueue = (removalListener == NullListener.INSTANCE) - ? LocalCache.>discardingQueue() - : new ConcurrentLinkedQueue>(); + ? LocalCache.discardingQueue() + : new ConcurrentLinkedQueue<>(); ticker = builder.getTicker(recordsTime()); entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries()); @@ -661,8 +660,8 @@ ValueReference copyFor( void notifyNewValue(@CheckForNull V newValue); /** - * Returns true if a new value is currently loading, regardless of whether or not there is an - * existing value. It is assumed that the return value of this method is constant for any given + * Returns true if a new value is currently loading, regardless of whether there is an existing + * value. It is assumed that the return value of this method is constant for any given * ValueReference instance. */ boolean isLoading(); @@ -1740,9 +1739,9 @@ Segment createSegment( /** * Gets the value from an entry. Returns null if the entry is invalid, partially-collected, - * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to - * cleanup stale entries. As such it should only be called outside of a segment context, such as - * during iteration. + * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean + * up stale entries. As such it should only be called outside a segment context, such as during + * iteration. */ @CheckForNull V getLiveValue(ReferenceEntry entry, long now) { @@ -1946,24 +1945,16 @@ static class Segment extends ReentrantLock { this.statsCounter = checkNotNull(statsCounter); initTable(newEntryArray(initialCapacity)); - keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue() : null; + keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null; - valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue() : null; + valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null; recencyQueue = - map.usesAccessQueue() - ? new ConcurrentLinkedQueue>() - : LocalCache.>discardingQueue(); + map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue(); - writeQueue = - map.usesWriteQueue() - ? new WriteQueue() - : LocalCache.>discardingQueue(); + writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue(); - accessQueue = - map.usesAccessQueue() - ? new AccessQueue() - : LocalCache.>discardingQueue(); + accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue(); } AtomicReferenceArray> newEntryArray(int size) { @@ -2208,15 +2199,12 @@ ListenableFuture loadAsync( CacheLoader loader) { final ListenableFuture loadingFuture = loadingValueReference.loadFuture(key, loader); loadingFuture.addListener( - new Runnable() { - @Override - public void run() { - try { - getAndRecordStats(key, hash, loadingValueReference, loadingFuture); - } catch (Throwable t) { - logger.log(Level.WARNING, "Exception thrown during refresh", t); - loadingValueReference.setException(t); - } + () -> { + try { + getAndRecordStats(key, hash, loadingValueReference, loadingFuture); + } catch (Throwable t) { + logger.log(Level.WARNING, "Exception thrown during refresh", t); + loadingValueReference.setException(t); } }, directExecutor()); @@ -2482,7 +2470,7 @@ void drainRecencyQueue() { // An entry may be in the recency queue despite it being removed from // the map . This can occur when the entry was concurrently read while a // writer is removing it from the segment or after a clear has removed - // all of the segment's entries. + // all the segment's entries. if (accessQueue.contains(e)) { accessQueue.add(e); } @@ -3266,7 +3254,7 @@ boolean reclaimValue(K key, int hash, ValueReference valueReference) { return false; } finally { unlock(); - if (!isHeldByCurrentThread()) { // don't cleanup inside of put + if (!isHeldByCurrentThread()) { // don't clean up inside of put postWriteCleanup(); } } @@ -3459,12 +3447,9 @@ public ListenableFuture loadFuture(K key, CacheLoader loader) { // *before* returning newValue from the cache query. return transform( newValue, - new Function() { - @Override - public V apply(V newValue) { - LoadingValueReference.this.set(newValue); - return newValue; - } + newResult -> { + LoadingValueReference.this.set(newResult); + return newResult; }, directExecutor()); } catch (Throwable t) { @@ -3807,19 +3792,19 @@ public boolean isEmpty() { */ long sum = 0L; Segment[] segments = this.segments; - for (int i = 0; i < segments.length; ++i) { - if (segments[i].count != 0) { + for (Segment segment : segments) { + if (segment.count != 0) { return false; } - sum += segments[i].modCount; + sum += segment.modCount; } if (sum != 0L) { // recheck unless no modifications - for (int i = 0; i < segments.length; ++i) { - if (segments[i].count != 0) { + for (Segment segment : segments) { + if (segment.count != 0) { return false; } - sum -= segments[i].modCount; + sum -= segment.modCount; } return sum == 0L; } @@ -3829,8 +3814,8 @@ public boolean isEmpty() { long longSize() { Segment[] segments = this.segments; long sum = 0; - for (int i = 0; i < segments.length; ++i) { - sum += Math.max(0, segments[i].count); // see https://github.com/google/guava/issues/2108 + for (Segment segment : segments) { + sum += Math.max(0, segment.count); // see https://github.com/google/guava/issues/2108 } return sum; } @@ -4398,7 +4383,7 @@ public E[] toArray(E[] a) { private static ArrayList toArrayList(Collection c) { // Avoid calling ArrayList(Collection), which may call back into toArray. - ArrayList result = new ArrayList(c.size()); + ArrayList result = new ArrayList<>(c.size()); Iterators.addAll(result, c.iterator()); return result; } @@ -4654,7 +4639,7 @@ public ImmutableMap getAll(Iterable keys) throws ExecutionExc } @Override - public final V apply(K key) { + public V apply(K key) { return autoDelegate.apply(key); } @@ -4672,7 +4657,7 @@ static class LocalManualCache implements Cache, Serializable { final LocalCache localCache; LocalManualCache(CacheBuilder builder) { - this(new LocalCache(builder, null)); + this(new LocalCache<>(builder, null)); } private LocalManualCache(LocalCache localCache) { @@ -4770,7 +4755,7 @@ static class LocalLoadingCache extends LocalManualCache LocalLoadingCache( CacheBuilder builder, CacheLoader loader) { - super(new LocalCache(builder, checkNotNull(loader))); + super(new LocalCache<>(builder, checkNotNull(loader))); } // LoadingCache methods diff --git a/guava/src/com/google/common/cache/CacheBuilder.java b/guava/src/com/google/common/cache/CacheBuilder.java index 668769b6ecfa..59ca757e59fe 100644 --- a/guava/src/com/google/common/cache/CacheBuilder.java +++ b/guava/src/com/google/common/cache/CacheBuilder.java @@ -96,7 +96,7 @@ *

  • accumulation of cache access statistics * * - *

    These features are all optional; caches can be created using all or none of them. By default + *

    These features are all optional; caches can be created using all or none of them. By default, * cache instances created by {@code CacheBuilder} will not perform any type of eviction. * *

    Usage example: @@ -230,13 +230,16 @@ public CacheStats snapshot() { }); static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0); - static final Supplier CACHE_STATS_COUNTER = - new Supplier() { - @Override - public StatsCounter get() { - return new SimpleStatsCounter(); - } - }; + /* + * We avoid using a method reference here for now: Inside Google, CacheBuilder is used from the + * implementation of a custom ClassLoader that is sometimes used as a system classloader. That's a + * problem because method-reference linking tries to look up the system classloader, and it fails + * because there isn't one yet. + * + * I would have guessed that a lambda would produce the same problem, but maybe it's safe because + * the lambda implementation is generated as a method in the _same class_ as the usage? + */ + static final Supplier CACHE_STATS_COUNTER = () -> new SimpleStatsCounter(); enum NullListener implements RemovalListener { INSTANCE; @@ -926,11 +929,11 @@ Ticker getTicker(boolean recordsTime) { * *

    Warning: after invoking this method, do not continue to use this cache builder * reference; instead use the reference this method returns. At runtime, these point to the - * same instance, but only the returned reference has the correct generic type information so as - * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in - * the class documentation above, configuring a builder and building your cache in a single - * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown - * by a cache operation at some undefined point in the future. + * same instance, but only the returned reference has the correct generic type information to + * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the + * class documentation above, configuring a builder and building your cache in a single statement. + * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache + * operation at some undefined point in the future. * *

    Warning: any exception thrown by {@code listener} will not be propagated to * the {@code Cache} user, only logged via a {@link Logger}. diff --git a/guava/src/com/google/common/cache/CacheLoader.java b/guava/src/com/google/common/cache/CacheLoader.java index 7a5e017d03d4..8c33f0541b77 100644 --- a/guava/src/com/google/common/cache/CacheLoader.java +++ b/guava/src/com/google/common/cache/CacheLoader.java @@ -26,7 +26,6 @@ import com.google.errorprone.annotations.CheckReturnValue; import java.io.Serializable; import java.util.Map; -import java.util.concurrent.Callable; import java.util.concurrent.Executor; /** @@ -153,7 +152,7 @@ public static CacheLoader from(Function function) { */ @CheckReturnValue public static CacheLoader from(Supplier supplier) { - return new SupplierToCacheLoader(supplier); + return new SupplierToCacheLoader<>(supplier); } private static final class FunctionToCacheLoader extends CacheLoader @@ -194,15 +193,9 @@ public V load(K key) throws Exception { } @Override - public ListenableFuture reload(final K key, final V oldValue) throws Exception { + public ListenableFuture reload(final K key, final V oldValue) { ListenableFutureTask task = - ListenableFutureTask.create( - new Callable() { - @Override - public V call() throws Exception { - return loader.reload(key, oldValue).get(); - } - }); + ListenableFutureTask.create(() -> loader.reload(key, oldValue).get()); executor.execute(task); return task; } diff --git a/guava/src/com/google/common/cache/CacheStats.java b/guava/src/com/google/common/cache/CacheStats.java index bf489e419d3e..7399adf23f40 100644 --- a/guava/src/com/google/common/cache/CacheStats.java +++ b/guava/src/com/google/common/cache/CacheStats.java @@ -152,8 +152,8 @@ public double missRate() { /** * Returns the total number of times that {@link Cache} lookup methods attempted to load new - * values. This includes both successful load operations, as well as those that threw exceptions. - * This is defined as {@code loadSuccessCount + loadExceptionCount}. + * values. This includes both successful load operations and those that threw exceptions. This is + * defined as {@code loadSuccessCount + loadExceptionCount}. * *

    Note: the values of the metrics are undefined in case of overflow (though it is * guaranteed not to throw an exception). If you require specific handling, we recommend diff --git a/guava/src/com/google/common/cache/LocalCache.java b/guava/src/com/google/common/cache/LocalCache.java index f2cbee3dbfdb..707bcedde14e 100644 --- a/guava/src/com/google/common/cache/LocalCache.java +++ b/guava/src/com/google/common/cache/LocalCache.java @@ -258,8 +258,8 @@ class LocalCache extends AbstractMap implements ConcurrentMap removalListener = builder.getRemovalListener(); removalNotificationQueue = (removalListener == NullListener.INSTANCE) - ? LocalCache.>discardingQueue() - : new ConcurrentLinkedQueue>(); + ? LocalCache.discardingQueue() + : new ConcurrentLinkedQueue<>(); ticker = builder.getTicker(recordsTime()); entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries()); @@ -663,8 +663,8 @@ ValueReference copyFor( void notifyNewValue(@Nullable V newValue); /** - * Returns true if a new value is currently loading, regardless of whether or not there is an - * existing value. It is assumed that the return value of this method is constant for any given + * Returns true if a new value is currently loading, regardless of whether there is an existing + * value. It is assumed that the return value of this method is constant for any given * ValueReference instance. */ boolean isLoading(); @@ -1740,12 +1740,11 @@ Segment createSegment( /** * Gets the value from an entry. Returns null if the entry is invalid, partially-collected, - * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to - * cleanup stale entries. As such it should only be called outside of a segment context, such as - * during iteration. + * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean + * up stale entries. As such it should only be called outside a segment context, such as during + * iteration. */ - @Nullable - V getLiveValue(ReferenceEntry entry, long now) { + @Nullable V getLiveValue(ReferenceEntry entry, long now) { if (entry.getKey() == null) { return null; } @@ -1946,24 +1945,16 @@ static class Segment extends ReentrantLock { this.statsCounter = checkNotNull(statsCounter); initTable(newEntryArray(initialCapacity)); - keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue() : null; + keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null; - valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue() : null; + valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null; recencyQueue = - map.usesAccessQueue() - ? new ConcurrentLinkedQueue>() - : LocalCache.>discardingQueue(); + map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue(); - writeQueue = - map.usesWriteQueue() - ? new WriteQueue() - : LocalCache.>discardingQueue(); + writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue(); - accessQueue = - map.usesAccessQueue() - ? new AccessQueue() - : LocalCache.>discardingQueue(); + accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue(); } AtomicReferenceArray> newEntryArray(int size) { @@ -2290,15 +2281,12 @@ ListenableFuture loadAsync( CacheLoader loader) { final ListenableFuture loadingFuture = loadingValueReference.loadFuture(key, loader); loadingFuture.addListener( - new Runnable() { - @Override - public void run() { - try { - getAndRecordStats(key, hash, loadingValueReference, loadingFuture); - } catch (Throwable t) { - logger.log(Level.WARNING, "Exception thrown during refresh", t); - loadingValueReference.setException(t); - } + () -> { + try { + getAndRecordStats(key, hash, loadingValueReference, loadingFuture); + } catch (Throwable t) { + logger.log(Level.WARNING, "Exception thrown during refresh", t); + loadingValueReference.setException(t); } }, directExecutor()); @@ -2564,7 +2552,7 @@ void drainRecencyQueue() { // An entry may be in the recency queue despite it being removed from // the map . This can occur when the entry was concurrently read while a // writer is removing it from the segment or after a clear has removed - // all of the segment's entries. + // all the segment's entries. if (accessQueue.contains(e)) { accessQueue.add(e); } @@ -3348,7 +3336,7 @@ boolean reclaimValue(K key, int hash, ValueReference valueReference) { return false; } finally { unlock(); - if (!isHeldByCurrentThread()) { // don't cleanup inside of put + if (!isHeldByCurrentThread()) { // don't clean up inside of put postWriteCleanup(); } } @@ -3481,7 +3469,7 @@ public LoadingValueReference() { } public LoadingValueReference(ValueReference oldValue) { - this.oldValue = (oldValue == null) ? LocalCache.unset() : oldValue; + this.oldValue = (oldValue == null) ? LocalCache.unset() : oldValue; } @Override @@ -3541,12 +3529,9 @@ public ListenableFuture loadFuture(K key, CacheLoader loader) { // *before* returning newValue from the cache query. return transform( newValue, - new com.google.common.base.Function() { - @Override - public V apply(V newValue) { - LoadingValueReference.this.set(newValue); - return newValue; - } + newResult -> { + LoadingValueReference.this.set(newResult); + return newResult; }, directExecutor()); } catch (Throwable t) { @@ -3919,19 +3904,19 @@ public boolean isEmpty() { */ long sum = 0L; Segment[] segments = this.segments; - for (int i = 0; i < segments.length; ++i) { - if (segments[i].count != 0) { + for (Segment segment : segments) { + if (segment.count != 0) { return false; } - sum += segments[i].modCount; + sum += segment.modCount; } if (sum != 0L) { // recheck unless no modifications - for (int i = 0; i < segments.length; ++i) { - if (segments[i].count != 0) { + for (Segment segment : segments) { + if (segment.count != 0) { return false; } - sum -= segments[i].modCount; + sum -= segment.modCount; } return sum == 0L; } @@ -3941,8 +3926,8 @@ public boolean isEmpty() { long longSize() { Segment[] segments = this.segments; long sum = 0; - for (int i = 0; i < segments.length; ++i) { - sum += segments[i].count; + for (Segment segment : segments) { + sum += segment.count; } return sum; } @@ -4540,7 +4525,7 @@ public E[] toArray(E[] a) { private static ArrayList toArrayList(Collection c) { // Avoid calling ArrayList(Collection), which may call back into toArray. - ArrayList result = new ArrayList(c.size()); + ArrayList result = new ArrayList<>(c.size()); Iterators.addAll(result, c.iterator()); return result; } @@ -4825,7 +4810,7 @@ public ImmutableMap getAll(Iterable keys) throws ExecutionExc } @Override - public final V apply(K key) { + public V apply(K key) { return autoDelegate.apply(key); } @@ -4843,7 +4828,7 @@ static class LocalManualCache implements Cache, Serializable { final LocalCache localCache; LocalManualCache(CacheBuilder builder) { - this(new LocalCache(builder, null)); + this(new LocalCache<>(builder, null)); } private LocalManualCache(LocalCache localCache) { @@ -4940,7 +4925,7 @@ static class LocalLoadingCache extends LocalManualCache LocalLoadingCache( CacheBuilder builder, CacheLoader loader) { - super(new LocalCache(builder, checkNotNull(loader))); + super(new LocalCache<>(builder, checkNotNull(loader))); } // LoadingCache methods