Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.cache;
 
 
 import java.util.Map;
This class provides a skeletal implementation of the Cache interface to minimize the effort required to implement this interface.

To implement a cache, the programmer needs only to extend this class and provide an implementation for the put(java.lang.Object,java.lang.Object) and Cache.getIfPresent(java.lang.Object) methods. getAllPresent(java.lang.Iterable) is implemented in terms of Cache.getIfPresent(java.lang.Object); putAll(java.util.Map) is implemented in terms of put(java.lang.Object,java.lang.Object), invalidateAll(java.lang.Iterable) is implemented in terms of invalidate(java.lang.Object). The method cleanUp() is a no-op. All other methods throw an java.lang.UnsupportedOperationException.

Author(s):
Charles Fry
Since:
10.0
 
 public abstract class AbstractCache<K, V> implements Cache<K, V> {

  
Constructor for use by subclasses.
 
   protected AbstractCache() {}

  

Since:
11.0
 
   @Override
   public V get(K keyCallable<? extends V> valueLoaderthrows ExecutionException {
     throw new UnsupportedOperationException();
   }

  
This implementation of getAllPresent lacks any insight into the internal cache data structure, and is thus forced to return the query keys instead of the cached keys. This is only possible with an unsafe cast which requires keys to actually be of type K.

Since:
11.0
 
   @Override
   public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
     Map<K, V> result = Maps.newLinkedHashMap();
     for (Object key : keys) {
       if (!result.containsKey(key)) {
         @SuppressWarnings("unchecked")
         K castKey = (K) key;
         result.put(castKeygetIfPresent(key));
       }
     }
     return ImmutableMap.copyOf(result);
   }

  

Since:
11.0
 
   @Override
   public void put(K key, V value) {
     throw new UnsupportedOperationException();
   }

  

Since:
12.0
 
   @Override
   public void putAll(Map<? extends K, ? extends V> m) {
     for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
       put(entry.getKey(), entry.getValue());
     }
   }
 
   @Override
  public void cleanUp() {}
  public long size() {
    throw new UnsupportedOperationException();
  }
  public void invalidate(Object key) {
    throw new UnsupportedOperationException();
  }

  

Since:
11.0
  public void invalidateAll(Iterable<?> keys) {
    for (Object key : keys) {
      invalidate(key);
    }
  }
  public void invalidateAll() {
    throw new UnsupportedOperationException();
  }
  public CacheStats stats() {
    throw new UnsupportedOperationException();
  }
  public ConcurrentMap<K, V> asMap() {
    throw new UnsupportedOperationException();
  }

  
Accumulates statistics during the operation of a Cache for presentation by Cache.stats(). This is solely intended for consumption by Cache implementors.

Since:
10.0
  @Beta
  public interface StatsCounter {
    
Records cache hits. This should be called when a cache request returns a cached value.

Parameters:
count the number of hits to record
Since:
11.0
    public void recordHits(int count);

    
Records cache misses. This should be called when a cache request returns a value that was not found in the cache. This method should be called by the loading thread, as well as by threads blocking on the load. Multiple concurrent calls to Cache lookup methods with the same key on an absent value should result in a single call to either recordLoadSuccess or recordLoadException and multiple calls to this method, despite all being served by the results of a single load operation.

Parameters:
count the number of misses to record
Since:
11.0
    public void recordMisses(int count);

    
Records the successful load of a new entry. This should be called when a cache request causes an entry to be loaded, and the loading completes successfully. In contrast to recordMisses(int), this method should only be called by the loading thread.

Parameters:
loadTime the number of nanoseconds the cache spent computing or retrieving the new value
    public void recordLoadSuccess(long loadTime);

    
Records the failed load of a new entry. This should be called when a cache request causes an entry to be loaded, but an exception is thrown while loading the entry. In contrast to recordMisses(int), this method should only be called by the loading thread.

Parameters:
loadTime the number of nanoseconds the cache spent computing or retrieving the new value prior to an exception being thrown
    public void recordLoadException(long loadTime);

    
Records the eviction of an entry from the cache. This should only been called when an entry is evicted due to the cache's eviction strategy, and not as a result of manual Cache.invalidate(java.lang.Object).
    public void recordEviction();

    
Returns a snapshot of this counter's values. Note that this may be an inconsistent view, as it may be interleaved with update operations.
    public CacheStats snapshot();
  }

  
A thread-safe AbstractCache.StatsCounter implementation for use by Cache implementors.

Since:
10.0
  @Beta
  public static class SimpleStatsCounter implements StatsCounter {
    private final AtomicLong hitCount = new AtomicLong();
    private final AtomicLong missCount = new AtomicLong();
    private final AtomicLong loadSuccessCount = new AtomicLong();
    private final AtomicLong loadExceptionCount = new AtomicLong();
    private final AtomicLong totalLoadTime = new AtomicLong();
    private final AtomicLong evictionCount = new AtomicLong();

    

Since:
11.0
    @Override
    public void recordHits(int count) {
      .addAndGet(count);
    }

    

Since:
11.0
    @Override
    public void recordMisses(int count) {
      .addAndGet(count);
    }
    @Override
    public void recordLoadSuccess(long loadTime) {
      .addAndGet(loadTime);
    }
    @Override
    public void recordLoadException(long loadTime) {
      .addAndGet(loadTime);
    }
    @Override
    public void recordEviction() {
    }
    @Override
    public CacheStats snapshot() {
      return new CacheStats(
          .get(),
          .get(),
          .get(),
          .get(),
          .get(),
          .get());
    }

    
Increments all counters by the values in other.
    public void incrementBy(StatsCounter other) {
      CacheStats otherStats = other.snapshot();
      .addAndGet(otherStats.hitCount());
      .addAndGet(otherStats.missCount());
      .addAndGet(otherStats.totalLoadTime());
      .addAndGet(otherStats.evictionCount());
    }
  }
New to GrepCode? Check out our FAQ X