package org.jboss.cache.eviction.minttl;

import org.jboss.cache.Fqn;
import org.jboss.cache.util.TestingUtil;
import org.jboss.cache.eviction.EvictionPolicyConfigBase;
import org.jboss.cache.eviction.FIFOConfiguration;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

/**
 * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
 * @since 2.1.0
 */
@Test(groups = {"functional"})
public class FIFOMinTTLTest extends MinTTLTestBase
{
   private Fqn fqn2 = Fqn.fromRelativeElements(region, "b");
   private Thread busyThread;
   private boolean busyThreadRunning = true;

   @Override
   protected EvictionPolicyConfigBase getEvictionPolicyConfig()
   {
      startBusyThread();
      FIFOConfiguration cfg = new FIFOConfiguration();
      cfg.setMaxNodes(1);
      return cfg;
   }

   @AfterMethod
   public void stopBusyThread()
   {
      busyThreadRunning = false;
      try
      {
         busyThread.join();
      }
      catch (InterruptedException e)
      {
      }
   }

   private void startBusyThread()
   {
      // start a thread to constantly put another node in the cache to make sure the maxNodes is exceeded.
      // this should only happen AFTER the main node is entered to guarantee FIFO.
      busyThreadRunning = true;
      busyThread = new Thread("BusyThread")
      {
         public void run()
         {
            try
            {
               cacheInitialisedLatch.await();
            }
            catch (InterruptedException e)
            {
               // do nothing
            }

            while (busyThreadRunning)
            {
               cache.put(fqn2, "k", "v");
               TestingUtil.sleepRandom(150);
            }
         }
      };

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