/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.eviction;

import org.jboss.cache.Region;

/**
 * Most Recently Used Algorithm.
 * <p/>
 * This algorithm will evict the most recently used cache entries from cache.
 * <p/>
 * Note: None of the Eviction classes are thread safe. It is assumed that an individual instance of an EvictionPolicy/
 * EvictionAlgorithm/EvictionQueue/EvictionConfiguration are only operated on by one thread at any given time.
 *
 * @author Daniel Huang (dhuang@jboss.org)
 * @version $Revision: 5671 $
 */
public class MRUAlgorithm extends BaseEvictionAlgorithm
{
   @Override
   protected EvictionQueue setupEvictionQueue(Region region) throws EvictionException
   {
      return new MRUQueue();
   }

   @Override
   protected boolean shouldEvictNode(NodeEntry ne)
   {
      // check the minimum time to live and see if we should not evict the node.  This check will
      // ensure that, if configured, nodes are kept alive for at least a minimum period of time.
      if (isYoungerThanMinimumTimeToLive(ne)) return false;

      MRUConfiguration config = (MRUConfiguration) region.getEvictionPolicyConfig();
      return evictionQueue.getNumberOfNodes() > config.getMaxNodes();
   }

   @Override
   protected void processVisitedNodes(EvictedEventNode evictedEventNode) throws EvictionException
   {
      super.processVisitedNodes(evictedEventNode);
      ((MRUQueue) evictionQueue).moveToTopOfStack(evictedEventNode.getFqn());
   }
}
