Поддерживайте кэш для выполнения приложения - PullRequest
0 голосов
/ 04 марта 2019

У меня есть легкий кеш, который я использую для отслеживания некоторых данных во время выполнения приложения,

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);
}

The private long timeToLive (ie 500) используется для элементов, срок действия которых истекает в зависимости от назначенного периода времени.Как мне сохранить его в течение всего времени выполнения приложения?

Я имею в виду, что могу использовать большое значение, но есть ли какой-нибудь способ Java сохранить его в течение всего времени?

...