Occurrence.java

80 lines | 1.89 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.cache.Cache;
import br.ufrgs.inf.prosoft.cache.KeyNotFoundException;
import br.ufrgs.inf.prosoft.memoizeit.graph.Node;

import java.util.List;
import java.util.Objects;

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

    private final String instance;
    private final long startTime;
    private final long endTime;

    public Occurrence(String instance, long startTime, long endTime) {
        this.instance = instance;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public String getInstance() {
        return instance;
    }

    public abstract Object getReturnValue();

    public abstract List<Parameter> getParameters();

    public long getStartTime() {
        return startTime;
    }

    public long getEndTime() {
        return endTime;
    }

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

    protected Occurrence getView(int depth) {
        return getConcrete().getView(depth);
    }

    protected Occurrence removeUnusedFields(Node<String> methodNode) {
        return loadConcrete().removeUnusedFields(methodNode);
    }

    protected void simulateCaching(Cache cache) {
        String key = getParameters().toString();
        try {
            Object cached = cache.get(key);
            if (!Objects.equals(cached, getReturnValue())) {
                cache.invalidate(key);
            }
        } catch (KeyNotFoundException ex) {
            cache.put(key, getReturnValue());
        }
    }

    public OccurrenceConcrete getConcrete() {
        return (OccurrenceConcrete) this;
    }

    public Occurrence loadConcrete() {
        return this;
    }

}