为应用程序运行时保持缓存活动

时间:2019-03-04 11:31:45

标签: java multithreading caching lru

我有一个轻量级缓存,用于跟踪应用程序运行时中的某些数据,

public class MemoryCache<K, T> {


    private long timeToLive;
    private LRUMap map;

    protected class CacheObject {

        public long lastAccessed = System.currentTimeMillis();
        public T value;

        protected CacheObject(T value) {
            this.value = value;
        }
    }

    public MemoryCache(long timeToLive, final long timerInterval, int maxItems) {

        this.timeToLive = timeToLive * 1000;

        map = new LRUMap(maxItems);

        if (this.timeToLive > 0 && timerInterval > 0) {

            Thread t = new Thread(new Runnable() {

                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(timerInterval * 1000);
                        } catch (InterruptedException ex) {
                        }
                        cleanup();
                    }
                }
            });

            t.setDaemon(true);
            t.start();
        }
    }

    public void put(K key, T value) {
        synchronized (map) {
            map.put(key, new CacheObject(value));
        }
    }

    @SuppressWarnings("unchecked")
    public T get(K key) {

        synchronized (map) {

            CacheObject c = (CacheObject) map.get(key);

            if (c == null)
                return null;
            else {
                c.lastAccessed = System.currentTimeMillis();
                return c.value;
            }
        }
    }

    public void remove(K key) {
        synchronized (map) {
            map.remove(key);
        }
    }

    public int size() {
        synchronized (map) {
            return map.size();
        }
    }

    @SuppressWarnings("unchecked")
    public void cleanup() {

        long now = System.currentTimeMillis();
        ArrayList<K> deleteKey = null;

        synchronized (map) {
            MapIterator itr = map.mapIterator();

            deleteKey = new ArrayList<K>((map.size() / 2) + 1);
            K key = null;
            CacheObject c = null;

            while (itr.hasNext()) {
                key = (K) itr.next();
                c = (CacheObject) itr.getValue();

                if (c != null && (now > (timeToLive + c.lastAccessed))) {
                    deleteKey.add(key);
                }
            }
        }

        for (K key : deleteKey) {
            synchronized (map) {
                map.remove(key);
            }

            Thread.yield();
        }
    }

}

在API中,我将其实例化,

@RestController
@RequestMapping("/api/v1/products")
public class ProductAPI {


    MemoryCache<String, Integer> cache = new MemoryCache<String, Integer>(500, 100, 100);
}

private long timeToLive (ie 500)用于根据分配的生存时间到期的项目。如何在整个应用程序运行时保持活动状态?

我的意思是我可以使用一个较大的值,但是,有没有Java方法可以使它在整个时间内保持活动状态?

0 个答案:

没有答案