Java tutorial
/* * (c) 2005 David B. Bracewell * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.davidbracewell.cache.impl; import com.davidbracewell.cache.AutoCalculatingCache; import com.davidbracewell.cache.CacheSpec; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.ExecutionException; /** * @author David B. Bracewell */ public class GuavaLoadingCache<K, V> extends AutoCalculatingCache<K, V> { private final LoadingCache<K, V> cache; public GuavaLoadingCache(CacheSpec<K, V> specification) { super(Preconditions.checkNotNull(specification)); Preconditions.checkNotNull(specification.getFunction()); CacheBuilder<K, V> cacheBuilder = GuavaCacheUtils.cacheBuilderFromSpec(specification); CacheLoader<K, V> loader = new CacheLoader<K, V>() { @Override public V load(K key) throws Exception { return function.apply(key); } }; if (specification.getRemovalListener() == null) { this.cache = cacheBuilder.build(loader); } else { this.cache = cacheBuilder.removalListener(specification.getRemovalListener()).build(loader); } } @Override public boolean containsKey(K key) { return cache.asMap().containsKey(key); } @Override public void put(K key, final V value) { cache.put(key, value); } @Override public long size() { return cache.size(); } @Override public void invalidateAll() { cache.invalidateAll(); } @Override public void invalidateAll(Iterable<? extends K> keys) { cache.invalidateAll(keys); } @Override public void invalidate(K key) { cache.invalidate(key); } @Override public void close() throws Exception { cache.cleanUp(); } @Override public V get(K key) { try { return cache.get(key); } catch (ExecutionException e) { throw Throwables.propagate(e); } } @Override public void refresh(K key) throws ExecutionException { cache.refresh(key); } }//END OF GuavaCache