/*
** Module   : PerThreadElement.java
** Abstract : represents a set of duplicate elements which are assigned to a
**            specific thread
**
** Copyright (c) 2009, Golden Code Development Corporation.
**
** -#- -I- --Date-- -----------------------Description------------------------
** 001 GES 20090318 Represents a set of duplicate elements which are assigned
**                  to a specific thread.
** 002 TJD 20230119 Allow restarting of Driver threads
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.goldencode.harness;

import java.util.*;
import java.util.concurrent.*;

/**
 * Represents a set of duplicate elements which are assigned to a specific
 * thread.
 * 
 * @param   <E>
 *          Type of element.
 */
public class PerThreadElement<E>
implements SubQueue<E>
{
   /** The contained elements. */
   private final LinkedBlockingQueue<E> queue;
   
   /** Reservation list. */
   private final Map<Thread, E> reserved = new HashMap<Thread, E>();
   
   /** Tasks pending recycling. */
   private final Map<Thread, E> pendingRecycling = new HashMap<Thread, E>();

   /** Already serviced list (each thread is only ever serviced once). */
   private final Set<Thread> serviced = new HashSet<Thread>();
   
   /** Synchronization primitive (more granular than "this"). */
   private final Object lock = new Object();
   
   /**
    * Construct an instance.
    *
    * @param    elements
    *           The queue elements to contain.
    */
   public PerThreadElement(List<E> elements)
   {
      queue = new LinkedBlockingQueue<E>(elements);
   }
   
   /**
    * Reports if there are any elements remaining in the queue. This can answer
    * the question of whether there will ever be elements available to
    * {@link #dequeue}. Note that due to dependencies between elements, it is
    * possible for a queue to be non-empty but to not yet be ready to accept
    * a <code>dequeue</code> request.
    *
    * @return   <code>true</code> if all queue elements have been dequeued.
    */
   public boolean isEmpty()
   {
      boolean empty = false;
      synchronized(lock)
      {
         if (pendingRecycling.containsKey(Thread.currentThread()))
         {
            // recycle test used by this thread
            queue.add(pendingRecycling.remove(Thread.currentThread()));
         }
      }
      // per thread elements are never empty and thus they are never removed from master queue 
      // as they can be reused for restarting threads
      return empty;
   }
   
   /**
    * Reports if the queue has elements to {@link #dequeue}. This will be
    * <code>false</code> if there are no elements remaining OR if the calling
    * thread has already retrieved an element from this instance.
    *
    * @return   <code>true</code> if the queue contains at least one element
    *           which is ready to be dequeued by the calling thread.
    */
   public boolean isReady()
   {
      boolean prev = false;
      boolean isEmpty = false;
      synchronized (lock)
      {
         prev = serviced.contains(Thread.currentThread());
         isEmpty = queue.isEmpty();
      }
      
      return !isEmpty && !prev;
   }
   
   /**
    * Reports if the queue acts as a barrier. A barrier is a sub-queue that
    * ends the search for elements until such time as the barrier sub-queue is
    * the first sub-queue. This is a mechanism to force all prior sub-queues to
    * be fully processed before any following sub-queues can be processed.
    * <p>
    * Barriers DO NOT have any elements of their own to return. Rather, they
    * just are a marker of known "sections" of the containing queue.
    *
    * @return   Always <code>false</code>.
    */
   public boolean isBarrier()
   {
      return false;
   }
   
   /**
    * Associates the next element in the queue with the caller, without
    * actually calling {@link #dequeue} which can block. This allows the
    * calling code to release any resources before the subsequent potentially
    * blocking operation. Any subsequent call to {@link #isReady} MUST take
    * this reservation into account. This means that all calls to this method
    * must be matched with a subsequent call to <code>dequeue</code>.
    *
    * @return   <code>true</code> if the reservation was successful. Otherwise
    *           the queue is not ready and caller MUST NOT call
    *           <code>dequeue</code>. 
    */
   public boolean reserve()
   {
      synchronized (lock)
      {
         Thread current = Thread.currentThread();
         
         if (!reserved.containsKey(current))
         {
            // try to dequeue the object
            E element = queue.poll();
            
            // there was an object to obtain so we must have been "ready"
            if (element != null)
            {
               // reserve it
               reserved.put(current, element);
               serviced.add(current);
               return true;
            }
         }
      }
      
      return false;
   }
   
   /**
    * Obtain the (only) element from the queue.
    *
    * @return   The element or <code>null</code> if the element was previously
    *           retrieved.
    */
   public E dequeue()
   {
      E element = null;
      
      synchronized (lock)
      {
         element = reserved.remove(Thread.currentThread());
         pendingRecycling.put(Thread.currentThread(), element);
      }
      
      return element;
   }
   
   /**
    * Reports if the subqueue can be ignored when checking if queue is empty
    *
    * @return   <code>true</code> if the queue can be ignored.
    */
   @Override
   public boolean isIgnored()
   {
      // once executed it can be ignored
      return !isReady();
   }}
