欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

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

程序员文章站 2022-04-16 14:56:55
...
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 {
    private final Map m_objects;
    private final Map 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());
        m_expiredObjects = Collections.synchronizedMap(new HashMap());
        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 Get(final String name, final Class type) {
        return (R) Get(name);
    }
}