001: package ri.cache.eviction;
002:
003: import javax.cache.CacheEntry;
004:
005: public abstract class AbstractCacheEntry<K, V> implements
006: CacheEntry<K, V> {
007:
008: private final K key;
009: private V value;
010:
011: private int hitCount;
012: private long lastAccessTime;
013: private long version;
014: private long lastUpdateTime;
015: private final long creationTime;
016: private final long ttl;
017:
018: public AbstractCacheEntry(K key, V value, long ttl) {
019: if (key == null)
020: throw new NullPointerException();
021: this .key = key;
022: this .value = value;
023: this .ttl = ttl;
024: creationTime = lastAccessTime = lastUpdateTime = System
025: .currentTimeMillis();
026: }
027:
028: public K getKey() {
029: return key;
030: }
031:
032: public long getVersion() {
033: return version;
034: }
035:
036: public long getCost() {
037: return 1;
038: }
039:
040: public boolean isValid() {
041: return getExpirationTime() > System.currentTimeMillis();
042: }
043:
044: public V getValue() {
045: return value;
046: }
047:
048: public V setValue(V obj) {
049: lastUpdateTime = System.currentTimeMillis();
050: ++version;
051: V oldValue = value;
052: value = obj;
053: return oldValue;
054: }
055:
056: public long getHits() {
057: return hitCount;
058: }
059:
060: public void touch() {
061: lastAccessTime = System.currentTimeMillis();
062: hitCount++;
063: }
064:
065: public abstract void discard();
066:
067: public long getLastAccessTime() {
068: return lastAccessTime;
069: }
070:
071: public long getLastUpdateTime() {
072: return lastUpdateTime;
073: }
074:
075: public long getCreationTime() {
076: return creationTime;
077: }
078:
079: public long getExpirationTime() {
080: return (ttl > 0) ? lastUpdateTime + ttl : Long.MAX_VALUE;
081: }
082:
083: public String toString() {
084: return super .toString() + " - key: '" + key + "'";
085: }
086:
087: // Two entries are equal if they are both valid and have equal keys and values
088: public boolean equals(Object obj) {
089: if (!(obj instanceof AbstractCacheEntry))
090: return false;
091: if (obj == null)
092: return false;
093: AbstractCacheEntry other = (AbstractCacheEntry) obj;
094:
095: if (!isValid() || !other.isValid())
096: return false;
097: if (key == null && other.key != null)
098: return false;
099: if (key != null && !key.equals(other.key))
100: return false;
101: if (value == null && other.value != null)
102: return false;
103: if (value != null && !value.equals(other.value))
104: return false;
105:
106: return true;
107: }
108:
109: public int hashCode() {
110: return key.hashCode() + 31 * value.hashCode();
111: }
112: }
|