Cache.java

50 lines | 1.11 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.Supplier;

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

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

    public void 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) {
        synchronized (key) {
            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) {
        synchronized (key) {
            V get = get(key);
            if (get != null) {
                return get;
            }
            get = supplier.get();
            put(key, get);
            return get;
        }
    }
}