// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package dbcache;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.spi.CachingProvider;

// this class must be subclassed to setup and teardown a JCache implementation properly
public abstract class DAL_Cache implements DAL {
    protected CachingProvider cp;
    protected CacheManager cm;
    protected Cache<Integer,Big> big_cache;
    protected Cache<String,Integer> counter_cache;
    private DAL real;
    public DAL_Cache(DAL real) {
        this.real = real;
    }
    @Override
    public Big getBig(int id) {
        Big res = big_cache.get(id);
        if(res == null) {
            res = real.getBig(id);
            big_cache.put(id,  res);
        }
        return res;
    }
    @Override
    public Integer getCounter(String id) {
        Integer res = counter_cache.get(id);
        if(res == null) {
            res = real.getCounter(id);
            counter_cache.put(id, res);
        }
        return res;
    }
    @Override
    public void incrementCounter(String id) {
        real.incrementCounter(id);
        counter_cache.put(id, real.getCounter(id));
    }
    @Override
    public void close() {
        counter_cache.close();
        big_cache.close();
        cm.close();
        cp.close();
        real.close();
    }
}
