Cache.java

46 lines | 1.005 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.function.Function;

/**
 *
 * @author romulo
 * @param <K>
 * @param <V>
 */
public interface Cache<K, V> {

    public V put(K key, V value, long timeToLive);

    public V put(K key, V value);

    public V get(K key);

    public void invalidate(K key);

    public default V computeIfAbsent(K key, Function<K, V> function, long timeToLive) {
        V get = get(key);
        if (get != null) {
            return get;
        }
        V apply = function.apply(key);
        put(key, apply, timeToLive);
        return apply;
    }

    public default V computeIfAbsent(K key, Function<K, V> function) {
        V get = get(key);
        if (get != null) {
            return get;
        }
        V apply = function.apply(key);
        put(key, apply);
        return apply;
    }
}