All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.anotheria.anoprise.cache.ExpiringCache Maven / Gradle / Ivy

Go to download

Collection of utils for different enterprise class projects. Among other stuff contains Caches, Mocking, DualCrud, MetaFactory and SessionDistributorService. Visit https://opensource.anotheria.net for details.

There is a newer version: 4.0.0
Show newest version
package net.anotheria.anoprise.cache;

import net.anotheria.moskito.core.predefined.CacheStats;

/**
 * A cache implementation where elements expire after some time.
 * @author another
 *
 * @param 
 * @param 
 */
public class ExpiringCache implements Cache{
	/**
	 * Expiration time for cache entries to become invalid.
	 */
	private long expirationTime;
	
	/**
	 * Internal cache delegate.
	 */
	private Cache> cache;
	/**
	 * Moskito cache stats of the internal cache delegate. Both caches work on the same cache stats object ( but different values of it).
	 */
	private CacheStats moskitoCacheStats;
	
	public ExpiringCache(String name, int aStartSize, int aMaxSize, long anExpirationTime, CacheFactory> underlyingCacheFactory){
		this(name, anExpirationTime, underlyingCacheFactory.create(name, aStartSize, aMaxSize));
	}

	public ExpiringCache(String name, long anExpirationTime, Cache> underlyingCache){
		cache = underlyingCache;
		expirationTime = anExpirationTime;
		moskitoCacheStats = cache.getCacheStats();
	}
	
	
	@Override public V get(K id) {
		CachedObjectWrapper wrapper = cache.get(id);
		if (wrapper==null)
			return null;
		long now = System.currentTimeMillis();
		
		
		if (now-wrapper.getTimestamp()>expirationTime){
			moskitoCacheStats.addExpired();
			remove(id);
			return null;
		}
		
		return wrapper.getObj();
	}

	public void put(K id, V cacheable) {
		cache.put(id, new CachedObjectWrapper(cacheable));
	}
	
	@Override public String toString(){
		return cache.toString()+", ExpirationTime: "+expirationTime;
	}
	
	@Override public void clear() {
		cache.clear();
	}

	@Override public void remove(K id) {
		cache.remove(id);
	}

	@Override public CacheStats getCacheStats() {
		return moskitoCacheStats;
	}
	
	void setExpirationTime(long anExpirationTime){
		expirationTime = anExpirationTime;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy