MultiCache.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
cache /
MultiCache.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.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author romulo
*/
public class MultiCache extends HashMap<Object, Object> implements Cache {
private final CachingPerformance cachingPerformance;
public MultiCache() {
this.cachingPerformance = new CachingPerformance();
}
public MultiCache(String name) {
this.cachingPerformance = new CachingPerformance(name);
}
public MultiCache(CachingPerformance cachingPerformance) {
this.cachingPerformance = cachingPerformance;
}
public CachingPerformance getCachingPerformance() {
return this.cachingPerformance;
}
@Override
public Object put(Object key, Object value, long timeToLive) {
Object put = put(key, value);
Thread thread = new Thread(() -> {
try {
Thread.sleep(timeToLive);
} catch (InterruptedException ex) {
Logger.getLogger(MultiCache.class.getName()).log(Level.SEVERE, "interrupted time to live");
}
MultiCache.super.remove(key);
});
thread.start();
return put;
}
@Override
public Object put(Object key, Object value) {
Object oldReference = super.put(key, value);
if (oldReference == null) {
this.cachingPerformance.registerSize(size());
}
return oldReference;
}
@Override
public Object get(Object key) {
Object get = super.get(key);
if (get == null) {
this.cachingPerformance.registerMiss();
} else {
this.cachingPerformance.registerHit();
}
return get;
}
@Override
public void invalidate(Object key) {
Object remove = this.remove(key);
if (remove != null) {
this.cachingPerformance.registerInvalidation();
}
}
}