GetterCache.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
cache /
GetterCache.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.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author romulo
* @param <V>
*/
public class GetterCache<V> {
private final CachingPerformance cachingPerformance;
private V result;
private boolean isFilled;
public GetterCache() {
this.isFilled = false;
this.cachingPerformance = new CachingPerformance();
}
public GetterCache(String name) {
this.isFilled = false;
this.cachingPerformance = new CachingPerformance(name);
}
public GetterCache(CachingPerformance cachingPerformance) {
this.isFilled = false;
this.cachingPerformance = cachingPerformance;
}
public V put(V value, long timeToLive) {
V put = put(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.result = null;
this.isFilled = false;
});
thread.start();
return put;
}
public V put(V value) {
this.result = value;
this.isFilled = true;
this.cachingPerformance.registerSize(1);
return this.result;
}
public V get() {
if (this.isFilled == false) {
this.cachingPerformance.registerMiss();
return null;
}
this.cachingPerformance.registerBytesHit(CachingPerformance.calculateObjectSize(this.result));
this.cachingPerformance.registerHit();
return this.result;
}
public void invalidate() {
this.isFilled = false;
this.result = null;
this.cachingPerformance.registerInvalidation();
}
public V computeIfAbsent(Supplier<V> supplier, long timeToLive) {
V get = get();
if (get != null) {
return get;
}
get = supplier.get();
put(get, timeToLive);
return get;
}
public V computeIfAbsent(Supplier<V> supplier) {
V get = get();
if (get != null) {
return get;
}
get = supplier.get();
put(get);
return get;
}
}