SingleCache.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
cache /
SingleCache.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ufrgs.inf.prosoft.cache;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author romulo
* @param <K>
* @param <V>
*/
public class SingleCache<K, V> implements Cache<K, V> {
private final CachingPerformance cachingPerformance;
private K lastInput;
private V result;
public SingleCache() {
this.cachingPerformance = new CachingPerformance();
}
public SingleCache(String name) {
this.cachingPerformance = new CachingPerformance(name);
}
public SingleCache(CachingPerformance cachingPerformance) {
this.cachingPerformance = cachingPerformance;
}
public CachingPerformance getCachingPerformance() {
return this.cachingPerformance;
}
@Override
public V put(K key, V value, long timeToLive) {
V put = put(key, value);
Thread thread = new Thread(() -> {
try {
Thread.sleep(timeToLive);
} catch (InterruptedException ex) {
Logger.getLogger(SingleCache.class.getName()).log(Level.SEVERE, "interrupted time to live");
}
this.lastInput = null;
this.result = null;
});
thread.start();
return put;
}
@Override
public V put(K key, V value) {
this.lastInput = key;
this.result = value;
this.cachingPerformance.registerSize(1);
return this.result;
}
@Override
public V get(K key) {
if (key.equals(this.lastInput)) {
this.cachingPerformance.registerHit();
this.cachingPerformance.registerBytesHit(CachingPerformance.calculateObjectSize(this.result));
return this.result;
}
this.cachingPerformance.registerMiss();
return null;
}
@Override
public void invalidate(K key) {
this.lastInput = null;
this.result = null;
this.cachingPerformance.registerInvalidation();
}
}