

package gov.va.med.cds.util;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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


public class LRUHashMap<K, V>
    extends
        LinkedHashMap<K, V>
{
    private static final long serialVersionUID = 1;
    private static final float HASH_TABLE_LOAD_FACTOR = 0.75f;
    private static final Log LOGGER = LogFactory.getLog( LRUHashMap.class );
    private int mapThreshold;


    public LRUHashMap( int aMapSize )
    {
        super( ( int )Math.ceil( aMapSize / HASH_TABLE_LOAD_FACTOR ) + 1, HASH_TABLE_LOAD_FACTOR, true );
        this.mapThreshold = aMapSize;
    }


    @Override
    protected boolean removeEldestEntry( Map.Entry<K, V> eldestEntry )
    {
        boolean removingEldest = ( size() > mapThreshold );
        if ( removingEldest && LOGGER.isDebugEnabled() )
        {
            LOGGER.debug( "Removing entry: " + eldestEntry.getKey() + " from map" );
        }

        return removingEldest;
    }


    /**
     * sets the threshold
     * 
     * @param newSize
     */
    public void reSize( int newSize )
    {
        this.mapThreshold = newSize;
    }


    /**
     * gets the threshold value
     * 
     * @return mapThreshold
     */
    public int getMapThreshold( )
    {
        return mapThreshold;
    }
}
