de.esprit.appsuite.task

## Class AbstractAsyncTask<C extends ApplicationContext>

- java.lang.Object
- - de.esprit.common.util.DumpableObject
  - - de.esprit.appsuite.launch.AbstractApplicationObject<C>
    - - de.esprit.appsuite.task.AbstractAsyncExecutable<C>
      - - de.esprit.appsuite.task.AbstractAsyncTask<C>

- All Implemented Interfaces:
    ApplicationObject<C>, AsyncExecutable<C>, AsyncTask<C>, CancellableTask, LocalCancellableTask, TaskMonitorSupport, TaskIdHolder, SimpleLogSupport, Dumpable, Executable, java.lang.Runnable
  Direct Known Subclasses:
    AbstractClientTask, AbstractOsProcessTask, AbstractServerTask, AbstractSwingTask, AbstractTimerTask, AppLaunchTask, ArchiveExtractTask, ArchiveListTask, DBLoadTask, ExecutorTask, StdinReaderTask, TaskCollection, WatchDogTask, ZipArchiverTask

      public abstract class AbstractAsyncTask<C extends ApplicationContext>
      extends AbstractAsyncExecutable<C>
      implements AsyncTask<C>

  This class encapsulates an asynchronously running task that is being executed within any `ExecutorService`. A task may have a `TaskMonitor` attached which is being notified about progress whereas the notification methods are called directly by the executing thread. The task can be cancelled any time with the `cancel()` call. This only works, if the `AbstractAsyncExecutable.isCancellable()` returns true. The task itself may decide not to be cancellable during critical phases. A task may produce a result which can be set (by the task itself) using `AbstractAsyncExecutable.setResult(Object)`. Any other thread may block waiting for the result with `awaitFinished()`.
  Author:
    Rainer Buesch

- - ### Field Summary

    - ### Fields inherited from class de.esprit.appsuite.task.AbstractAsyncExecutable

      `childTaskRef, isTestMode, monitorController, resultRef, stateFlag`

  - ### Constructor Summary

    Constructors
    Modifier | Constructor and Description
    --- | ---
    `protected` | `AbstractAsyncTask(C ctx)`
    `protected` | `AbstractAsyncTask(C ctx, LogChannel logCh)`
    `protected` | `AbstractAsyncTask(C ctx, LogChannel logCh, java.lang.String taskName, TaskType taskType)`
    `protected` | `AbstractAsyncTask(C ctx, LogChannel logCh, TaskType taskType)`
    `protected` | `AbstractAsyncTask(C ctx, java.lang.String taskName)`
    `protected` | `AbstractAsyncTask(C ctx, java.lang.String taskName, TaskType taskType)`
    `protected` | `AbstractAsyncTask(C ctx, TaskType taskType)`

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `<R> R` | `awaitFinished()` Awaits non-interruptibly the finish of this task.
    `<R> R` | `awaitFinished(long timeout, java.util.concurrent.TimeUnit unit)` Waits until the task has finished but runs in a TimeoutException if it did not finish within the expected time.
    `void` | `awaitStarted()` Waits until the task actually has started running.
    `void` | `cancel()` Flags the task as being cancelled.
    `protected TaskId` | `createTaskId()` Is called at submit time.
    `protected void` | `deregisterTask()` Removes registration of the the task from the `TaskManager`
    `protected void` | `doOnFinish()` Is called in ANY CASE when the task has finished.
    `protected void` | `doOnStart()` Is called when the task actually has started.
    `protected void` | `doOnSuccess()` Is called when the task has succeeded.
    `abstract void` | `executeAsync()` Must be overridden to perform the async part.
    `void` | `executeChildTask(AsyncTask childTask)` Runs the childTask in the default executor of the `ApplicationContext`.
    `void` | `executeChildTask(AsyncTask childTask, java.util.concurrent.ExecutorService pool)` Runs the childTask asynchronously as a task on it's own.
    `protected java.util.concurrent.Future` | `getCurrentFuture()` Returns the `Future` of this task as returned by the thread-pool.
    `int` | `getMaxChildTasks()`
    `int` | `getPriority()` Returns the Tread execution priority.
    `long` | `getProcessingDuration()` Tells how long the task has been running since STARTED
    `long` | `getStartTime()` Returns the time in millis when this task started execution
    `StopWatch` | `getStopWatch()` Returns the tasks `StopWatch` for analyzing elapsed execution times.
    `protected void` | `handleFinish()`
    `protected void` | `handleStart()`
    `protected void` | `handleSuccess()`
    `boolean` | `isRegisterForCancel()` Tells whether the task is being registered at the `TaskManager` to be accessible for cancellation.
    `boolean` | `isRunning()` Returns true from the time on the task has been submitted until it has finished.
    `void` | `notifyProceeded(java.lang.Object result, int step, int maxSteps, java.lang.String message)` Notifies progress to an attached task-monitor.
    `protected void` | `registerTask()` Registers the task at the `TaskManager`
    `void` | `releaseStart()` Releases the task for execution after submission.
    `void` | `run()` This method defines a clean task body around the asynchronously called `executeAsync()` method.
    `protected void` | `setCurrentFuture(java.util.concurrent.Future future)`
    `void` | `setMaxChildTasks(int maxChildTasks)` Sets the max number of child-tasks that are being executed within this main task.
    `void` | `setPriority(int priority)` Sets the thread-priority for execution.
    `void` | `setRegisterForCancel(boolean isRegister)`
    `void` | `setReleaseTimeout(long releaseTimeoutMillis)` Defines a timeout for waiting on the release gate after having started.
    `TaskId` | `submit()` Submits this task for execution to the default application thread pool
    `TaskId` | `submit(java.util.concurrent.ExecutorService pool)` Submits this task for execution to the given thread pool
    `protected TaskId` | `submitInternal(java.util.concurrent.ExecutorService pool)`
    `ToString` | `toString(ToString s)` This method allows subclasses to add values to the existing ToString of the superclass.
    `boolean` | `wasSucceeded()` Tells whether this task has succeeded

    - ### Methods inherited from class de.esprit.appsuite.task.AbstractAsyncExecutable

      `addMonitor, checkCancelled, checkForErrorAndRethrow, clearMonitors, createRunStateFlag, doOnCancel, doOnFailure, execute, executeSubTask, getError, getMaxProgressSteps, getMonitorCount, getMonitors, getName, getProgressStepCount, getResult, getRunStateFlag, getTaskId, getType, handleCancellation, handleFailure, hasError, hasMonitor, isCancellable, registerTaskStateChange, removeMonitor, resetProgress, setCancellable, setLogLevel, setMaxProgressSteps, setMonitor, setName, setName, setResult, setRunStateFlag, setTaskId, setType, shouldFireMonitor, sleepChecked, wasCancelled`

    - ### Methods inherited from class de.esprit.appsuite.launch.AbstractApplicationObject

      `getApplicationContext, getLogChannel, isLogDebug, isLogVerbose, logDebug, logDump, logError, logError, logFatal, logInfo, logVerbose, logWarning, setLogChannel`

    - ### Methods inherited from class de.esprit.common.util.DumpableObject

      `configureDumpHeadlineLength, configureDumpMaxElementsPrinted, copyDumpStringValues, copyToStringValues, createDumpHeader, toDumpString, toDumpString, toString`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

    - ### Methods inherited from interface de.esprit.appsuite.task.AsyncTask

      `getError, hasError, setName`

    - ### Methods inherited from interface de.esprit.appsuite.task.AsyncExecutable

      `checkCancelled, checkForErrorAndRethrow, executeSubTask, getName, getResult, getRunStateFlag, getTaskId, getType, handleCancellation, handleFailure, isCancellable, setCancellable, setName, setResult, setRunStateFlag, sleepChecked`

    - ### Methods inherited from interface de.esprit.appsuite.launch.ApplicationObject

      `getApplicationContext`

    - ### Methods inherited from interface de.esprit.common.type.Executable

      `execute`

    - ### Methods inherited from interface de.esprit.appsuite.task.monitor.TaskMonitorSupport

      `addMonitor, clearMonitors, getMonitorCount, getMonitors, hasMonitor, removeMonitor`

    - ### Methods inherited from interface de.esprit.common.log.SimpleLogSupport

      `getLogChannel, isLogDebug, isLogVerbose, logDebug, logDump, logError, logError, logFatal, logInfo, logVerbose, logWarning, setLogChannel`

    - ### Methods inherited from interface de.esprit.appsuite.task.CancellableTask

      `wasCancelled`

    - ### Methods inherited from interface de.esprit.appsuite.task.TaskIdHolder

      `getTaskId`

    - ### Methods inherited from interface de.esprit.common.type.Dumpable

      `toDumpString, toDumpString, toString`

- - ### Constructor Detail

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx)

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx,
                           TaskType taskType)

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx,
                           LogChannel logCh,
                           TaskType taskType)

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx,
                           LogChannel logCh)

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx,
                           java.lang.String taskName,
                           TaskType taskType)

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx,
                           java.lang.String taskName)

    - #### AbstractAsyncTask

          protected AbstractAsyncTask(C ctx,
                           LogChannel logCh,
                           java.lang.String taskName,
                           TaskType taskType)

  - ### Method Detail

    - #### submit

          public TaskId submit()
                        throws java.lang.Exception

      Description copied from interface: `AsyncTask`
      Submits this task for execution to the default application thread pool
      Specified by:
        `submit` in interface `AsyncTask<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception` - if the pool is busy

    - #### submit

          public TaskId submit(java.util.concurrent.ExecutorService pool)
                        throws java.lang.Exception

      Description copied from interface: `AsyncTask`
      Submits this task for execution to the given thread pool
      Specified by:
        `submit` in interface `AsyncTask<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception` - if the pool is busy

    - #### setMaxChildTasks

          public final void setMaxChildTasks(int maxChildTasks)

      Sets the max number of child-tasks that are being executed within this main task. Is used when two progress bars are being driven, a main-progress-bar and a child-progress-bar. Implies that `AbstractAsyncExecutable.executeSubTask(AsyncExecutable)` will be called maxChildTasks times.
      See Also:
        `getMaxChildTasks()`

    - #### getMaxChildTasks

          public final int getMaxChildTasks()

      See Also:
        `setMaxChildTasks(int)`

    - #### getPriority

          public final int getPriority()

      Returns the Tread execution priority. Note that after execution the priority of the executing thread is resetted.
      See Also:
        `setPriority(int)`

    - #### setPriority

          public final void setPriority(int priority)

      Sets the thread-priority for execution.
      Parameters:
        `priority` - the thread-priority
      See Also:
        `setPriority(int)`

    - #### getStopWatch

          public final StopWatch getStopWatch()

      Returns the tasks `StopWatch` for analyzing elapsed execution times.

    - #### getStartTime

          public final long getStartTime()

      Returns the time in millis when this task started execution

    - #### getProcessingDuration

          public final long getProcessingDuration()

      Description copied from interface: `AsyncTask`
      Tells how long the task has been running since STARTED
      Specified by:
        `getProcessingDuration` in interface `AsyncTask<C extends ApplicationContext>`

    - #### getCurrentFuture

          protected java.util.concurrent.Future getCurrentFuture()

      Returns the `Future` of this task as returned by the thread-pool.

    - #### setCurrentFuture

          protected final void setCurrentFuture(java.util.concurrent.Future future)

    - #### submitInternal

          protected final TaskId submitInternal(java.util.concurrent.ExecutorService pool)
                                         throws java.lang.Exception

      Throws:
        `java.lang.Exception`

    - #### setReleaseTimeout

          public final void setReleaseTimeout(long releaseTimeoutMillis)

      Description copied from interface: `AsyncTask`
      Defines a timeout for waiting on the release gate after having started. If set to a positive value, then the task would wait on the release gate until the timeout is exceeded or `AsyncTask.releaseStart()` is being called explicitly. This allows for getting the `TaskId` on submit but having more control about the actual start time of the task. By default the task does not wait on the release gate.
      Specified by:
        `setReleaseTimeout` in interface `AsyncTask<C extends ApplicationContext>`
      See Also:
        `AsyncTask.releaseStart()`

    - #### releaseStart

          public final void releaseStart()

      Description copied from interface: `AsyncTask`
      Releases the task for execution after submission.
      Specified by:
        `releaseStart` in interface `AsyncTask<C extends ApplicationContext>`
      See Also:
        `AsyncTask.setReleaseTimeout(long)`

    - #### awaitStarted

          public final void awaitStarted()
                                  throws java.lang.InterruptedException

      Waits until the task actually has started running.
      Specified by:
        `awaitStarted` in interface `AsyncTask<C extends ApplicationContext>`
      Throws:
        `java.lang.InterruptedException`

    - #### createTaskId

          protected TaskId createTaskId()

      Is called at submit time. Each submit of a task creates a new `TaskId` which is added to the `RunStateFlag`.

    - #### executeAsync

          public abstract void executeAsync()
                                     throws java.lang.Exception

      Must be overridden to perform the async part. From within this method you may directly call `notifyProceeded(Object, int, int, String)` in order to notify about task progress. Note: the running task should periodically call `AbstractAsyncExecutable.checkCancelled()` in order to detect cancellation.
      Specified by:
        `executeAsync` in interface `AsyncExecutable<C extends ApplicationContext>`
      Specified by:
        `executeAsync` in class `AbstractAsyncExecutable<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`
      See Also:
        `for synchronous execution`

    - #### executeChildTask

          public final void executeChildTask(AsyncTask childTask,
                              java.util.concurrent.ExecutorService pool)
                                      throws java.lang.Exception

      Runs the childTask asynchronously as a task on it's own. This task blocks until the childTask has completed. The childTask shares the `RunStateFlag` with the main-task. As the childTask runs in a different execution thread it has got it's own `TaskId` which is added to the main-TaskId. canceling the main-task in fact cancels the childTask. During childTask execution the monitor will receive CHILD_STARTED, CHILD_SUCCEEDED and CHILD_FINISHED notifications. Any PROGRESS notifications in between are associated to the current childTask.
      Specified by:
        `executeChildTask` in interface `AsyncTask<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`

    - #### executeChildTask

          public final void executeChildTask(AsyncTask childTask)
                                      throws java.lang.Exception

      Runs the childTask in the default executor of the `ApplicationContext`.
      Specified by:
        `executeChildTask` in interface `AsyncTask<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`
      See Also:
        `executeChildTask(AsyncTask, ExecutorService)`

    - #### cancel

          public void cancel()

      Flags the task as being cancelled. The next call to `AbstractAsyncExecutable.checkCancelled()` will result a `CancellationException` being thrown. As a result `AbstractAsyncExecutable.doOnCancel()` is being called on the task.
      Specified by:
        `cancel` in interface `LocalCancellableTask`

    - #### run

          public final void run()

      This method defines a clean task body around the asynchronously called `executeAsync()` method. It manages the `RunStateFlag` and drives the `TaskMonitor`.
      Specified by:
        `run` in interface `java.lang.Runnable`

    - #### handleStart

          protected final void handleStart()
                                    throws java.lang.Exception

      Overrides:
        `handleStart` in class `AbstractAsyncExecutable<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`

    - #### handleSuccess

          protected final void handleSuccess()

      Overrides:
        `handleSuccess` in class `AbstractAsyncExecutable<C extends ApplicationContext>`

    - #### handleFinish

          protected final void handleFinish()

      Overrides:
        `handleFinish` in class `AbstractAsyncExecutable<C extends ApplicationContext>`

    - #### doOnStart

          protected void doOnStart()
                            throws java.lang.Exception

      Is called when the task actually has started. Maybe overridden to perform any task preparation. Note that an Exception thrown here will cause the task to fail.
      Throws:
        `java.lang.Exception`

    - #### doOnSuccess

          protected void doOnSuccess()

      Is called when the task has succeeded. Maybe overridden to perform any task finalization. Note that any Exceptions thrown are caught and just logged but do NOT affect the task.

    - #### doOnFinish

          protected void doOnFinish()

      Is called in ANY CASE when the task has finished. Maybe overridden to perform any task finalization. Note that any Exceptions thrown are caught and just logged but do NOT affect the task.

    - #### isRegisterForCancel

          public final boolean isRegisterForCancel()

      Tells whether the task is being registered at the `TaskManager` to be accessible for cancellation.
      Specified by:
        `isRegisterForCancel` in interface `AsyncTask<C extends ApplicationContext>`

    - #### setRegisterForCancel

          public final void setRegisterForCancel(boolean isRegister)

    - #### registerTask

          protected void registerTask()

      Registers the task at the `TaskManager`

    - #### deregisterTask

          protected void deregisterTask()

      Removes registration of the the task from the `TaskManager`

    - #### notifyProceeded

          public void notifyProceeded(java.lang.Object result,
                             int step,
                             int maxSteps,
                             java.lang.String message)

      Description copied from class: `AbstractAsyncExecutable`
      Notifies progress to an attached task-monitor. In fact delegates to `TaskMonitor.taskProceeded(RunStateFlag, Object, int, int, String)` IMPORTANT: the 'result' object passed here MUST NOT be changed any more by the running task. If this cannot be guaranteed make sure that you pass a copy here! A copy is not made automatically because in many cases this would not be necessary. The progressCount value is typically the same as returned by `AbstractAsyncExecutable.getMaxProgressSteps()`. Similar the step value is typically the same as returned by `AbstractAsyncExecutable.getProgressStepCount()`. Anyway you are allowed to pass these values explicitly because a running task may have complex behavior during runtime. For example: a task may not know at start time how many steps it will do - at that time the ProgressBar shows up floating. But later on it has calculated the steps it will need and then it performs step notifications for driving the progress bar on a percentage value.
      Specified by:
        `notifyProceeded` in interface `AsyncExecutable<C extends ApplicationContext>`
      Overrides:
        `notifyProceeded` in class `AbstractAsyncExecutable<C extends ApplicationContext>`
      Parameters:
        `result` - any intermediate result that may be achieved so far
        `step` - the count of progress steps
        `maxSteps` - the expected maximum number of progress steps
        `message` - any textual message explaining what the progress is

    - #### wasSucceeded

          public final boolean wasSucceeded()

      Tells whether this task has succeeded

    - #### isRunning

          public boolean isRunning()

      Description copied from interface: `AsyncTask`
      Returns true from the time on the task has been submitted until it has finished. Thus it reflects the time frame where we have got a valid TaskId.
      Specified by:
        `isRunning` in interface `AsyncTask<C extends ApplicationContext>`

    - #### awaitFinished

          public final <R> R awaitFinished()

      Awaits non-interruptibly the finish of this task. Even if the task was cancelled this method blocks until the cancellation has been handled by the task.
      Specified by:
        `awaitFinished` in interface `AsyncTask<C extends ApplicationContext>`
      Returns:
        the result of this task, if any or null if the task was cancelled.

    - #### awaitFinished

          public final <R> R awaitFinished(long timeout,
                            java.util.concurrent.TimeUnit unit)
                                throws java.util.concurrent.TimeoutException

      Description copied from interface: `AsyncTask`
      Waits until the task has finished but runs in a TimeoutException if it did not finish within the expected time. When the task runs into a timeout it is automatically cancelled.
      Specified by:
        `awaitFinished` in interface `AsyncTask<C extends ApplicationContext>`
      Returns:
        the result of this task, if any or null if the task was cancelled or is timed out.
      Throws:
        `java.util.concurrent.TimeoutException`
      See Also:
        `AsyncTask.awaitFinished()`

    - #### toString

          public ToString toString(ToString s)

      Description copied from interface: `Dumpable`
      This method allows subclasses to add values to the existing ToString of the superclass. Usually subclasses only need to override this method.
      Specified by:
        `toString` in interface `Dumpable`
      Overrides:
        `toString` in class `DumpableObject`

Copyright © 2014 EsprIT-Systems. All Rights Reserved.