package ru.yandex.webmaster3.core.semantic.semantic_document_parser.util.collections;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 7/18/11
 * Time: 7:06 PM
 * To change this template use File | Settings | File Templates.
 */
public class LRUQueue<T> implements MemoQueue<T> {

    public final int MAX_SIZE;
    public final int memoryLimitPercent;
    private long hitCount = 0;
    private final LinkedHashMap<T, Integer> map;

    public LRUQueue(final int maxSize, final int memoryLimitPercent) {
        this.MAX_SIZE = maxSize;
        this.memoryLimitPercent = memoryLimitPercent;
        map = new LinkedHashMap<T, Integer>(maxSize, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(final Map.Entry<T, Integer> tIntegerEntry) {
                return this.size() > MAX_SIZE || (Runtime.getRuntime().freeMemory() * 100 / Runtime.getRuntime().totalMemory() > memoryLimitPercent);
            }
        };
    }


    @Override
    public synchronized boolean add(final T element) {
        final Integer wasInQueue = map.put(element, 1);
        return wasInQueue==null;
    }

    @Override
    public synchronized long getHitRatio() {
        return hitCount;
    }
}
