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 {
    /**
     * 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 implements LocalCache {
    private static final long MAX_SIZE = 65535;

    private static final long EXPIRE_TIME = 10;

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

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

            @Override
            public Optional 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);
    }

}

你可能感兴趣的:(杂谈)