Cache.java

46 lines | 997 B 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.Supplier;

/**
 *
 * @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, Supplier<V> supplier, long timeToLive) {
        V get = get(key);
        if (get != null) {
            return get;
        }
        get = supplier.get();
        put(key, get, timeToLive);
        return get;
    }

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