设计高效的线程安全的缓存(java并发编程实战5.6)

几乎每一个应用都会使用到缓存, 但是设计高效的线程安全的缓存并不简单. 如:

Java代码   收藏代码
  1. public interface Computable<A, V> {   
  2.     V compute(A arg) throws InterruptedException;   
  3. }   
  4.   
  5. public class ExpensiveFunction   
  6.         implements Computable<String, BigInteger> {   
  7.     // 模拟一个耗时操作  
  8.     public BigInteger compute(String arg) {   
  9.     // ...  
  10.         return new BigInteger(arg);   
  11.     }   
  12. }   
  13.   
  14. public class Memorizer1<A, V> implements Computable<A, V> {   
  15.     private final Map<A, V> cache = new HashMap<A, V>();   
  16.     private final Computable<A, V> c;   
  17.   
  18.     public Memorizer1(Computable<A, V> c) {   
  19.         this.c = c;   
  20.     }   
  21.     // 使用synchronized同步整个方法解决线程安全  
  22.     public synchronized V compute(A arg) throws InterruptedException {   
  23.         V result = cache.get(arg);   
  24.         if (result == null) {   
  25.             result = c.compute(arg);   
  26.             cache.put(arg, result);   
  27.         }   
  28.         return result;   
  29.     }   
  30. }  

Memorizer1使用HashMap缓存计算结果. 如果能在缓存中取出参数对应的结果, 就直接返回缓存的数据, 避免了重复进行代价昂贵的计算. 由于HashMap不是线程安全的, Memorizer1同步整个compute方法, 避免重复计算的同时, 牺牲了并发执行compute方法的机会, 此种设计甚至可能导致性能比没有缓存更差.

使用ConcurrentHashMap代替HashMap, 同时取消对compute方法的同步可以极大的改善性能:

Java代码   收藏代码
  1. public class Memorizer2<A, V> implements Computable<A, V> {   
  2.     private final Map<A, V> cache = new ConcurrentHashMap<A, V>();   
  3.     private final Computable<A, V> c;   
  4.   
  5.     public Memorizer2(Computable<A, V> c) { this.c = c; }   
  6.   
  7.     public V compute(A arg) throws InterruptedException {   
  8.         V result = cache.get(arg);   
  9.         if (result == null) {   
  10.             result = c.compute(arg);   
  11.             cache.put(arg, result);   
  12.         }   
  13.         return result;   
  14.     }   
  15. }   

ConcurrentHashMap是线程安全的, 并且具有极好的并发性能. 但是该设计仍存在问题: 无法避免所有的重复的计算. 有时这是可以的, 但对于一些要求苛刻的系统, 重复计算可能会引发严重的问题. Memorizer2的问题在于一个线程在执行compute方法的过程中, 其他线程以相同的参数调用compute方法时, 无法从缓存中获知已有线程正在进行该参数的计算的信息, 因此造成了重复计算的发生. 针对这一点, 可以改进缓存的设计:

Java代码   收藏代码
  1. public class Memorizer3<A, V> implements Computable<A, V> {   
  2.     // 改为缓存Future  
  3.     private final Map<A, Future<V>> cache   
  4.             = new ConcurrentHashMap<A, Future<V>>();   
  5.     private final Computable<A, V> c;   
  6.   
  7.     public Memorizer3(Computable<A, V> c) { this.c = c; }   
  8.   
  9.     public V compute(final A arg) throws InterruptedException {   
  10.         Future<V> f = cache.get(arg);   
  11.         if (f == null) {   
  12.             Callable<V> eval = new Callable<V>() {   
  13.                 public V call() throws InterruptedException {   
  14.                     return c.compute(arg);   
  15.                 }   
  16.             };   
  17.             FutureTask<V> ft = new FutureTask<V>(eval);   
  18.             f = ft;   
  19.         // 在计算开始前就将Future对象存入缓存中.  
  20.             cache.put(arg, ft);   
  21.             ft.run(); // call to c.compute happens here   
  22.         }   
  23.         try {   
  24.         // 如果缓存中存在arg对应的Future对象, 就直接调用该Future对象的get方法.  
  25.         // 如果实际的计算还在进行当中, get方法将被阻塞, 直到计算完成  
  26.             return f.get();   
  27.         } catch (ExecutionException e) {   
  28.             throw launderThrowable(e.getCause());   
  29.         }   
  30.     }   
  31. }   

Memorizer3中的缓存系统看起来已经相当完美: 具有极好的并发性能, 也不会存在重复计算的问题. 真的吗? 不幸的是Memorizer3仍然存在重复计算的问题, 只是相对于Memorizer2, 重复计算的概率降低了一些. cache.get(arg)的结果为null, 不代表cache.put(arg, ft)时cache中依旧没有arg对应的Future, 因此直接调用cache.put(arg, ft)是不合理的:

Java代码   收藏代码
  1. public class Memorizer<A, V> implements Computable<A, V> {   
  2.     private final ConcurrentMap<A, Future<V>> cache   
  3.         = new ConcurrentHashMap<A, Future<V>>();   
  4.     private final Computable<A, V> c;   
  5.   
  6.     public Memorizer(Computable<A, V> c) { this.c = c; }   
  7.   
  8.     public V compute(final A arg) throws InterruptedException {   
  9.         while (true) {   
  10.             Future<V> f = cache.get(arg);   
  11.             if (f == null) {   
  12.                 Callable<V> eval = new Callable<V>() {   
  13.                     public V call() throws InterruptedException {   
  14.                         return c.compute(arg);   
  15.                     }   
  16.                 };   
  17.                 FutureTask<V> ft = new FutureTask<V>(eval);   
  18.         // 使用putIfAbsent测试是否真的将ft存入了缓存, 如果存入失败, 说明cache中已经存在arg对应的future对象  
  19.         // 否则才进行计算.  
  20.                 f = cache.putIfAbsent(arg, ft);   
  21.                 if (f == null) { f = ft; ft.run(); }   
  22.             }   
  23.             try {   
  24.                 return f.get();   
  25.             } catch (CancellationException e) {   
  26.         // 当计算被取消时, 从缓存中移除arg-f键值对  
  27.                 cache.remove(arg, f);   
  28.             } catch (ExecutionException e) {   
  29.                 throw launderThrowable(e.getCause());   
  30.             }   
  31.         }   
  32.     }   
  33. }   

至此才真正实现了高效且线程安全的缓存.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值