
package com.zaxxer.hikari.pool;

import java.sql.Connection;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.zaxxer.hikari.util.AbstractBagEntry;

/**
 * Entry used in the ConcurrentBag to track Connection instances.
 *
 * @author Brett Wooldridge
 */
public final class PoolBagEntry extends AbstractBagEntry
{
   public final Connection connection;
   public long lastOpenTime;
   public volatile boolean evicted;
   public volatile boolean aborted;
   
   protected long lastAccess;

   private volatile ScheduledFuture<?> endOfLife;

   public PoolBagEntry(final Connection connection, final BaseHikariPool pool) {
      this.connection = connection;
      this.lastAccess = System.currentTimeMillis();

      final long maxLifetime = pool.configuration.getMaxLifetime();
      if (maxLifetime > 0) {
         endOfLife = pool.houseKeepingExecutorService.schedule(new Runnable() {
            public void run()
            {
               // If we can reserve it, close it
               if (pool.connectionBag.reserve(PoolBagEntry.this)) {
                  pool.closeConnection(PoolBagEntry.this);
               }
               else {
                  // else the connection is "in-use" and we mark it for eviction by pool.releaseConnection() or the housekeeper
                  PoolBagEntry.this.evicted = true;
               }
            }
         }, maxLifetime, TimeUnit.MILLISECONDS);
      }
   }

   void cancelMaxLifeTermination()
   {
      if (endOfLife != null) {
         endOfLife.cancel(false);
      }
   }

   @Override
   public String toString()
   {
      return "Connection......" + connection + "\n"
           + "  Last  access.." + lastAccess + "\n"
           + "  Last open....." + lastOpenTime + "\n"
           + "  State........." + super.toString();
   }
}

