Occurrence.java

78 lines | 2.253 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.memoizeit;

import br.ufrgs.inf.prosoft.memoizeit.cache.Cache;
import br.ufrgs.inf.prosoft.memoizeit.utils.Action;
import br.ufrgs.inf.prosoft.memoizeit.utils.ObjectUtils;
import java.util.List;

/**
 *
 * @author romulo
 */
public class Occurrence {

    private final String instance;
    private final Object returnValue;
    private final List<Object> parameters;
    private final long startTime;
    private final long endTime;
    private boolean truncated;

    public Occurrence(String instance, Object returnValue, List<Object> parameters, long startTime, long endTime) {
        this.instance = instance;
        this.returnValue = returnValue;
        this.parameters = parameters;
        this.startTime = startTime;
        this.endTime = endTime;
        this.truncated = true;
    }

    public String getInstance() {
        return instance;
    }

    public Object getReturnValue() {
        return this.returnValue;
    }

    public List<Object> getParameters() {
        return this.parameters;
    }

    public long getExecutionTime() {
        return this.endTime - this.startTime;
    }

    protected Occurrence getView(int depth) {
        if (!this.truncated) {
            return this;
        }
        this.truncated = false;
        Object returnValue = ObjectUtils.deepCopy(this.returnValue);
        Action onTruncate = () -> {
            this.truncated = true;
        };
        ObjectUtils.truncateObject(returnValue, depth, onTruncate);
        List<Object> parameters = ObjectUtils.deepCopy(this.parameters);
        ObjectUtils.truncateObject(parameters, depth, onTruncate);
        Occurrence occurrence = new Occurrence(this.instance, returnValue, parameters, this.startTime, this.endTime);
        return occurrence;
    }

    protected void simulateCaching(Cache cache) {
        String key = this.parameters.toString();
        Object cached = cache.get(key);
        if (cached == null) {
            cache.put(key, this.returnValue);
        } else if (!cached.equals(this.returnValue)) {
            cache.invalidate(key);
        }
    }

}