GetterCache.java

69 lines | 1.76 kB Blame History Raw Download
/*
 * 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
 */
public class GetterCache {

    private final CachingPerformance cachingPerformance;
    private Object result;
    private boolean isFilled;

    public GetterCache() {
        this.isFilled = false;
        this.cachingPerformance = new CachingPerformance();
    }

    public GetterCache(CachingPerformance cachingPerformance) {
        this.isFilled = false;
        this.cachingPerformance = cachingPerformance;
    }

    public Object put(Object value, long timeToLive) {
        Object 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 Object put(Object value) {
        this.result = value;
        this.isFilled = true;
        this.cachingPerformance.registerSize(1);
        return this.result;
    }

    public Object get() {
        if (this.isFilled == false) {
            this.cachingPerformance.registerMiss();
            return null;
        }
        this.cachingPerformance.registerHit();
        return this.result;
    }

    public void invalidate() {
        this.isFilled = false;
        this.result = null;
        this.cachingPerformance.registerInvalidation();
    }

}