Cache.java

51 lines | 1.252 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.Optional;
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) throws KeyNotFoundException;

    public void invalidate(K key);

    public default V computeIfAbsent(K key, Supplier<V> supplier, long timeToLive) {
        synchronized (Optional.ofNullable(key)) {
            try {
                return get(key);
            } catch (KeyNotFoundException ex) {
                V get = supplier.get();
                put(key, get, timeToLive);
                return get;
            }
        }
    }

    public default V computeIfAbsent(K key, Supplier<V> supplier) {
        synchronized (Optional.ofNullable(key)) {
            try {
                return get(key);
            } catch (KeyNotFoundException ex) {
                V get = supplier.get();
                put(key, get);
                return get;
            }
        }
    }
}