ProtectedTimerTask.java

/*
** Module   : ProtectedTimerTask.java
** Abstract : Task that can be scheduled to a ProtectedTimer.
**
** Copyright (c) 2004-2017, Golden Code Development Corporation.
**
** -#- -I- --Date-- --JPRM-- ----------------Description---------------------
** 001 SVL 20090720   @43237 Created initial version. Task that can be
**                           scheduled to a ProtectedTimer.
*/
/*
** 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 may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

package com.goldencode.p2j.util;

import java.util.concurrent.*;

/**
 * A task that can be scheduled for one-time or repeated execution by a {@link
 * ProtectedTimer}.
 * <p>
 * Implementations of this class should be designed to catch and handle
 * <code>OutOfMemoryError</code> to the degree possible.
 */
public abstract class ProtectedTimerTask
implements Delayed,
           Runnable
{
   /** Current task status. */
   private TaskStatus taskStatus = TaskStatus.VIRGIN;

   /** Interval between the subsequent executions of the task. */
   private long periodicalDelay = 0;

   /** Absolute time (in milliseconds) of the next execution of the task. */
   private long nextExecutionTime = 0;

   /**
    * Main task code. Should be implemented into subclasses.
    */
   public abstract void run();

   /**
    * Returns the remaining delay associated with this timer task, in the
    * given time unit.
    *
    * @param  timeUnit
    *         the time unit
    *
    * @return the remaining delay; zero or negative values indicate that the
    *         delay has already elapsed
    */
   public long getDelay(TimeUnit timeUnit)
   {
      long delay = nextExecutionTime - System.currentTimeMillis();
      return timeUnit.convert(delay, TimeUnit.MILLISECONDS);
   }

   /**
    * Compares the delay of this timer task with the delay of the specified
    * task. Returns a negative integer, zero, or a positive integer as delay
    * of this task is less than, equal to, or greater than the delay of the
    * specified task.
    *
    * @param  delayed
    *         the timer task which delay should be compared to the delay of
    *         this task.
    *
    * @return a negative integer, zero, or a positive integer as delay of this
    *         task is less than, equal to, or greater than the delay of the
    *         specified task. 
    */
   public int compareTo(Delayed delayed)
   {
      Long delay1 = getDelay(TimeUnit.MILLISECONDS);
      Long delay2 = delayed.getDelay(TimeUnit.MILLISECONDS);
      return delay1.compareTo(delay2);
   }

   /**
    * Cancels the task. 
    */
   public synchronized void cancel()
   {
      taskStatus = TaskStatus.CANCELLED;
   }

   /**
    * Determines whether this task is cancelled.
    *
    * @return See above.
    */
   public synchronized boolean isCancelled()
   {
      return taskStatus == TaskStatus.CANCELLED;
   }
   
   /**
    * Prepares the task for its initial execution.
    *
    * @param initialDelay
    *        Delay before execution of the task.
    * @param periodicalDelay
    *        Interval between the subsequent executions of the task.
    */
   void initialSchedule(long initialDelay, long periodicalDelay)
   {
      if (taskStatus != TaskStatus.VIRGIN)
      {
         throw new IllegalStateException(
                                   "Task is already scheduled or cancelled!");
      }

      if (initialDelay < 0)
      {
         throw new IllegalArgumentException("Initial delay should be >= 0!");
      }

      if (periodicalDelay < 0)
      {
         throw new IllegalArgumentException(
                                          "Periodical delay should be >= 0!");
      }

      this.periodicalDelay = periodicalDelay;
      nextExecutionTime = System.currentTimeMillis() + initialDelay;
      taskStatus = TaskStatus.SCHEDULED;
   }

   /**
    * Prepares the task for the next execution.
    *
    * @return <code>true</code> if the task was successfully rescheduled.
    *         <code>false</code> if task is completed and shouldn't be
    *         rescheduled.
    */
   boolean reschedule()
   {
      if (periodicalDelay > 0 && !isCancelled())
      {
         nextExecutionTime = System.currentTimeMillis() + periodicalDelay;
         return true;
      }
      else
      {
         return false;
      }
   }

   /**
    * Possible task states.
    */
   private enum TaskStatus
   {
      /** The task wasn't ever scheduled. */
      VIRGIN,

      /** The task was scheduled to a timer. */
      SCHEDULED,

      /** The task was cancelled. */
      CANCELLED
   }
}