1 28 29 package com.caucho.util; 30 31 51 public class TimedCache<K,V> { 52 private LruCache<K,TimedCache.Entry<V>> _cache; 53 private long _expireInterval; 54 55 61 public TimedCache(int capacity, long expireInterval) 62 { 63 _cache = new LruCache<K,Entry<V>>(capacity); 64 65 _expireInterval = expireInterval; 66 } 67 68 71 public V put(K key, V value) 72 { 73 Entry<V> oldValue = _cache.put(key, new Entry<V>(_expireInterval, value)); 74 75 if (oldValue != null) 76 return oldValue.getValue(); 77 else 78 return null; 79 } 80 81 84 public V get(K key) 85 { 86 Entry<V> entry = _cache.get(key); 87 88 if (entry == null) 89 return null; 90 91 if (entry.isValid()) 92 return entry.getValue(); 93 else { 94 _cache.remove(key); 95 96 return null; 97 } 98 } 99 100 103 static class Entry<V> implements CacheListener { 104 private long _expireInterval; 105 private long _checkTime; 106 private V _value; 107 108 Entry(long expireInterval, V value) 109 { 110 _expireInterval = expireInterval; 111 _value = value; 112 113 _checkTime = Alarm.getCurrentTime(); 114 } 115 116 boolean isValid() 117 { 118 return Alarm.getCurrentTime() < _checkTime + _expireInterval; 119 } 120 121 V getValue() 122 { 123 return _value; 124 } 125 126 public void removeEvent() 127 { 128 if (_value instanceof CacheListener) 129 ((CacheListener) _value).removeEvent(); 130 } 131 } 132 } 133 134 | Popular Tags |