Guava Cache之返回值为null抛出异常解决方案

问题描述

描述:对于方法“V get(key, loader) throws ExecutionException”loader的返回值不能为null,否则会抛出异常,文档描述如下:

Warning: as with {@link CacheLoader#load}, {@code loader} must not return
* {@code null}; it may either return a non-null value or throw an exception.

解决方案

方案:使用Optional对结果进行包装。

public interface LocalCache<K, V> {
    /**
     * Returns the value associated with {@code key} in this cache, or
     * {@code null} if there is no cached value for {@code key}.
     *
     **/
    V get(K key) throws Exception;

    /**
     * Associates {@code value} with {@code key} in this cache. If the cache
     * previously contained a value associated with {@code key}, the old value
     * is replaced by {@code value}.
     *
     **/
    void put(K key, V value);

    /**
     * Discards any cached value for key {@code key}.
     */
    void remove(Object key);
}
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Optional;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

public class LocalCacheImpl<K, V> implements LocalCache<K, V> {
    private static final long MAX_SIZE = 65535;

    private static final long EXPIRE_TIME = 10;

    private Cache<K, Optional<V>> caches = CacheBuilder.newBuilder().maximumSize(MAX_SIZE)
            .expireAfterAccess(EXPIRE_TIME, TimeUnit.SECONDS).removalListener(new RemovalListener<K, Optional<V>>() {
                @Override
                public void onRemoval(RemovalNotification<K, Optional<V>> notification) {
                    // TODO
                }
            }).build();

    @Override
    public V get(K key) throws Exception {
        Optional<V> opt = caches.get(key, new Callable<Optional<V>>() {

            @Override
            public Optional<V> call() throws Exception {
                // TODO获取数据,加入缓存
                return Optional.fromNullable(null);
            }

        });
        return opt.isPresent() ? opt.get() : null;
    }

    @Override
    public void put(K key, V value) {
        caches.put(key, Optional.of(value));
    }

    @Override
    public void remove(Object key) {
        caches.invalidate(key);
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值