Cache.java

50 lines | 1.079 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;

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

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

  void put(K key, V value);

  V get(K key) throws KeyNotFoundException;

  void invalidate(K key);

  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;
      }
    }
  }

  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;
      }
    }
  }
}