一个简单的内存缓存实现--一段漂亮的代码

转自:http://www.oschina.net/code/snippet_55577_3887

 1 package test;

 2 

 3 import java.util.Map;

 4 import java.util.WeakHashMap;

 5 import java.util.concurrent.ConcurrentHashMap;

 6 import java.util.concurrent.locks.Lock;

 7 import java.util.concurrent.locks.ReentrantLock;

 8 

 9 public final class SimpleCache<K,V> {

10 

11     private final Lock lock = new ReentrantLock();

12     private final int maxCapacity;

13     private final Map<K,V> eden;

14     private final Map<K,V> longterm;

15 

16     public SimpleCache(int maxCapacity) {

17         this.maxCapacity = maxCapacity;

18         this.eden = new ConcurrentHashMap<K,V>(maxCapacity);

19         this.longterm = new WeakHashMap<K,V>(maxCapacity);

20     }

21 

22     public V get(K k) {

23         V v = this.eden.get(k);

24         if (v == null) {

25             lock.lock();

26             try{

27                 v = this.longterm.get(k);

28             }finally{

29                 lock.unlock();

30             }

31             if (v != null) {

32                 this.eden.put(k, v);

33             }

34         }

35         return v;

36     }

37 

38     public void put(K k, V v) {

39         if (this.eden.size() >= maxCapacity) {

40             lock.lock();

41             try{

42                 this.longterm.putAll(this.eden);

43             }finally{

44                 lock.unlock();

45             }

46             this.eden.clear();

47         }

48         this.eden.put(k, v);

49     }

50 }

实现思路其实很简单,但是包装做的很好,很巧妙,值得新手借鉴。

你可能感兴趣的:(内存)