MultiCache.java

87 lines | 2.279 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.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author romulo
 * @param <K>
 * @param <V>
 */
public class MultiCache<K, V> implements Cache<K, V> {

    private final HashMap<K, V> map;
    private final CachingPerformance cachingPerformance;

    public MultiCache() {
        this.cachingPerformance = new CachingPerformance();
        this.map = new HashMap<>();
    }

    public MultiCache(String name) {
        this.cachingPerformance = new CachingPerformance(name);
        this.map = new HashMap<>();
    }

    public MultiCache(CachingPerformance cachingPerformance) {
        this.cachingPerformance = cachingPerformance;
        this.map = new HashMap<>();
    }

    public CachingPerformance getCachingPerformance() {
        return this.cachingPerformance;
    }

    @Override
    public V put(K key, V value, long timeToLive) {
        V put = put(key, value);
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(timeToLive);
            } catch (InterruptedException ex) {
                Logger.getLogger(MultiCache.class.getName()).log(Level.SEVERE, "interrupted time to live");
            }
            this.map.remove(key);
        });
        thread.start();
        return put;
    }

    @Override
    public V put(K key, V value) {
        V oldReference = this.map.put(key, value);
        if (oldReference == null) {
            this.cachingPerformance.registerSize(this.map.size());
        }
        return oldReference;
    }

    @Override
    public V get(K key) {
        V get = this.map.get(key);
        if (get == null) {
            this.cachingPerformance.registerMiss();
        } else {
            this.cachingPerformance.registerHit();
            this.cachingPerformance.registerBytesHit(CachingPerformance.calculateObjectSize(get));
        }
        return get;
    }

    @Override
    public void invalidate(K key) {
        V remove = this.map.remove(key);
        if (remove != null) {
            this.cachingPerformance.registerInvalidation();
        }
    }

}