用java.util.concurrent包来实现高速缓存

接口

public interface Computable<A,V> {
V compute(A args);
}
计算式很耗时间的话可以将结果缓存,缓存程序如下:

public class Memorizer<A, V> implements Computable<A, V> {
/*
* 该类主要功能是实现高速缓存,缓存计算结果
* 该类唯一的缺点在于判定f是否为null的时候接近完美
*
*/

//使用ConcurrentHashMap来缓存可以起到同步的作用,而Future可以避免重复工作(检查的时候都为空,同时计算)
private final ConcurrentHashMap<A, Future<V>> cache = new ConcurrentHashMap<A, Future<V>>();
private Computable<A,V> c;

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

public V compute(final A args) {
   while (true) {
    Future<V> f = cache.get(args);
    if (f == null) {
     Callable<V> eval = new Callable<V>() {

      public V call() throws Exception {
       return c.compute(args);
      }
     };
     FutureTask<V> ft = new FutureTask<V>(eval);
     f = cache.putIfAbsent(args, ft);
     if (f == null) {
      f = ft;
      ft.run();
     }
     try {
      return f.get();
     } catch (InterruptedException e) {
      cache.remove(args,f);
     } catch (ExecutionException e) {
      e.printStackTrace();
     }
    }

   }
}
}

转载于:https://www.cnblogs.com/macula7/archive/2010/03/11/1960507.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值