缓存设计

来源:互联网 发布:数据库查询去掉重复 编辑:程序博客网 时间:2024/06/10 07:49
public interface Computable<A, V> {

    V compute(A arg) throws InterruptedException;

}



public class ExpensiveFunctuion implements Computable<String, Integer> {

    public Integer compute(String arg) throws InterruptedException {
        //do..............
        return new Integer(arg);
    }

}



public class Memoizer3<A, V> implements Computable<A, V> {

    private final ConcurrentMap<A, FutureTask<V>> cache = new ConcurrentHashMap<A, FutureTask<V>>();
    private final Computable<A, V> c;

    // performance is  good
    public V compute(final A arg) throws InterruptedException {
        FutureTask<V> f = cache.get(arg);
        if (f == null) {
            Callable eval = new Callable() {
                public Object call() throws Exception {
                    return c.compute(arg);
                }
            };
            FutureTask<V> ft = new FutureTask<V>(eval);
            f = cache.putIfAbsent(arg, ft);
            if(f==null){
                f=ft;
                ft.run();
            }
            ft.run();
        }

        try {
            return f.get();
        } catch (Exception e) {
            cache.remove(arg,f);
        }
        return null;
    }

    public Memoizer3(Computable<A, V> c) {
        this.c = c;
    }

}

0 0
原创粉丝点击