com.droidlogix.dbflare.a2e.DbFlareResultCache Maven / Gradle / Ivy
package com.droidlogix.dbflare.a2e;
import com.google.common.primitives.Longs;
import java.lang.ref.SoftReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* This class will handle the caching of result. It will cache those parse
* JSON results based on the endpoint name and query string
* Code based from https://explainjava.com/simple-in-memory-cache-java/
* @author John Pili
* @since 23/11/19
*/
public class DbFlareResultCache implements IDbFlareCache
{
private final ConcurrentHashMap> items = new ConcurrentHashMap<>();
private final DelayQueue delayedCacheObjects = new DelayQueue<>();
public DbFlareResultCache()
{
Thread cleanupThread = new Thread(() -> {
while(!Thread.currentThread().isInterrupted())
{
try
{
DbFlareDelayedCacheObject dbFlareDelayedCacheObject = delayedCacheObjects.take();
items.remove(dbFlareDelayedCacheObject.getKey(), dbFlareDelayedCacheObject.getReference());
}
catch(InterruptedException interruptionException)
{
Thread.currentThread().interrupt();
}
}
});
cleanupThread.setDaemon(true);
cleanupThread.start();
}
@Override
public void set(String key, Object value, long periodInMillis)
{
try
{
if (key == null)
{
return;
}
if (value != null)
{
long expiryTime = System.currentTimeMillis() + periodInMillis;
//System.out.println("Inserting key: " + key + " expiry = " + Long.toString(expiryTime));
SoftReference