Java实现一个简单的内存缓存类

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SimpleCache<T> {
	private final Map<String, T> m_objects;
	private final Map<String, Long> m_expiredObjects;
	private final long m_lExpireTime;
	private final ExecutorService m_executor;
	public SimpleCache() {
		this(500);
	}
	public SimpleCache(final int nExpireTime) {
		m_objects = Collections.synchronizedMap(new HashMap<String, T>());
		m_expiredObjects = Collections.synchronizedMap(new HashMap<String, Long>());
		m_lExpireTime = nExpireTime;
		m_executor = Executors.newFixedThreadPool(256);
		Executors.newScheduledThreadPool(5).scheduleWithFixedDelay(RemoveExpiredObjects(), m_lExpireTime / 2,
				m_lExpireTime, TimeUnit.SECONDS);
	}
	private final Runnable RemoveExpiredObjects() {
		return new Runnable() {
			public void run() {
				for (final String name : m_expiredObjects.keySet()) {
					if (System.currentTimeMillis() > m_expiredObjects.get(name)) {
						m_executor.execute(CreateRemoveRunnable(name));
					}
				}
			}
		};
	}
	private final Runnable CreateRemoveRunnable(final String name) {
		return new Runnable() {
			public void run() {
				m_objects.remove(name);
				m_expiredObjects.remove(name);
			}
		};
	}
	public long GetExpireTime() {
		return m_lExpireTime;
	}
	public void Put(final String name, final T obj) {
		Put(name, obj, m_lExpireTime);
	}
	public void Put(final String name, final T obj, final long expireTime) {
		m_objects.put(name, obj);
		m_expiredObjects.put(name, System.currentTimeMillis() + expireTime * 1000);
	}
	public T Get(final String name) {
		final Long expireTime = m_expiredObjects.get(name);
		if (expireTime == null)
			return null;
		if (System.currentTimeMillis() > expireTime) {
			m_executor.execute(CreateRemoveRunnable(name));
			return null;
		}
		return m_objects.get(name);
	}
	@SuppressWarnings("unchecked")
	public <R extends T> R Get(final String name, final Class<R> type) {
		return (R) Get(name);
	}
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:mysql计算经纬度亮点之间的距离

下一篇:NSNotificationCenter 用法