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
* @param <K>
* @param <V>
*/
public class MultiCache<K, V> implements Cache<K, V> {
private static final boolean CACHE_REGISTER_SIZE = System.getenv("CACHE_REGISTER_SIZE") != null && System.getenv("CACHE_REGISTER_SIZE").equals("true");
private final HashMap<K, V> map;
private final CachePerformance cachingPerformance;
private static final Logger LOGGER = Logger.getLogger(Cache.class.getName());
public MultiCache() {
this(new CachePerformance());
}
public MultiCache(String name) {
this(new CachePerformance(name));
}
public MultiCache(CachePerformance cachingPerformance) {
this.cachingPerformance = cachingPerformance;
this.map = new HashMap<>();
}
public CachePerformance getCachingPerformance() {
return this.cachingPerformance;
}
@Override
public void put(K key, V value, long timeToLive) {
put(key, value);
Thread thread = new Thread(() -> {
try {
Thread.sleep(timeToLive);
} catch (InterruptedException ex) {
LOGGER.log(Level.SEVERE, "interrupted time to live");
}
invalidate(key);
});
thread.start();
}
@Override
public void put(K key, V value) {
invalidate(key);
this.map.put(key, value);
if (CACHE_REGISTER_SIZE) {
this.cachingPerformance.registerEvent(EventType.ADDITION, String.valueOf(value.hashCode()), CachePerformance.calculateObjectSize(value));
} else {
this.cachingPerformance.registerEvent(EventType.ADDITION, String.valueOf(value.hashCode()));
}
this.cachingPerformance.registerSize(this.map.size());
}
@Override
public V get(K key) {
V get = this.map.get(key);
if (get == null) {
this.cachingPerformance.registerEvent(EventType.MISS);
} else {
if (CACHE_REGISTER_SIZE) {
this.cachingPerformance.registerEvent(EventType.HIT, String.valueOf(get.hashCode()), CachePerformance.calculateObjectSize(get));
} else {
this.cachingPerformance.registerEvent(EventType.HIT, String.valueOf(get.hashCode()));
}
}
return get;
}
@Override
public void invalidate(K key) {
V remove = this.map.remove(key);
if (remove != null) {
if (CACHE_REGISTER_SIZE) {
this.cachingPerformance.registerEvent(EventType.INVALIDATION, String.valueOf(remove.hashCode()), CachePerformance.calculateObjectSize(remove));
} else {
this.cachingPerformance.registerEvent(EventType.INVALIDATION, String.valueOf(remove.hashCode()));
}
}
}
}