edu.rice.cs.plt.concurrent
Class TaskController<R>

java.lang.Object
  extended by edu.rice.cs.plt.concurrent.TaskController<R>
All Implemented Interfaces:
ResolvingThunk<R>, Thunk<R>, Future<R>
Direct Known Subclasses:
ExecutorTaskController, IncrementalTaskController, PollingTaskController, ProcessTaskController

public abstract class TaskController<R>
extends Object
implements ResolvingThunk<R>, Future<R>

Provides access to a concurrent task that produces a value. Extends standard Future behavior with an initial non-running state; also provides a variety of additional methods.

To implement a concrete instance, a subclass must provide doStart(), doStop(), and, optionally, discard(). The state field and related TaskController.State class hierarchy is protected, rather than private, in order to facilitate subclasses that modify the set and behavior of internal states; these should be treated as private by most subclasses.


Nested Class Summary
protected  class TaskController.CanceledStartingState
          A StartingState that has been canceled while waiting for startup to complete.
protected  class TaskController.CanceledState
          Has been successfully canceled.
protected  class TaskController.CancelingState
          Canceled while running; waiting for termination to complete.
protected  class TaskController.CleanlyFinishedState
          Finished with a result.
protected  class TaskController.ComputingState
          Any state in which the task has already been asked to compute a result.
protected  class TaskController.ExecutionExceptionState
          Finished with an ExecutionException.
protected  class TaskController.FinishedState
          Any state for a task that has finished.
protected  class TaskController.FreshStartingState
          Simple instance of StartingState.
protected  class TaskController.FreshState
          Initial state.
protected  class TaskController.InternalExceptionState
          Finished with a RuntimeException.
protected  class TaskController.RunningState
          Startup has completed and we're waiting for a result.
protected  class TaskController.StartingState
          FreshState.start() has been invoked, but startup is not yet complete.
protected  class TaskController.State
          An internal state for the controller, implementing the controller's core behavior.
static class TaskController.Status
           
protected  class TaskController.WaitingState
          Any state in which the task must be started before it can complete.
 
Field Summary
protected  AtomicReference<TaskController.State> state
          Current internal state; should only be modified with AtomicReference.compareAndSet(V, V).
 
Constructor Summary
protected TaskController()
           
 
Method Summary
 Option<R> attemptGet(long timeout)
          Try to get the result within the given amount of time.
 Option<R> attemptGet(long timeout, TimeUnit unit)
          Try to get the result within the given amount of time.
 boolean cancel()
          Request that the task be abandoned, and that any resources associated with it be disposed.
 boolean cancel(boolean stopRunning)
          Request that the task be abandoned, and that any resources associated with it be disposed.
protected  void discard()
          Clean up after the task has completed.
protected abstract  void doStart()
          Begin computation and call started().
protected abstract  void doStop()
          Terminate computation and call stopped().
protected  void finishedCleanly(R result)
          Called when running has completed and produced a value.
protected  void finishedWithImplementationException(RuntimeException e)
          Called when the runner implementation encounters an exception.
protected  void finishedWithTaskException(Exception e)
          Called when the running task terminates early with an exception.
 ListenerSet.Sink finishListeners()
          Access the ListenerSet responding to the completion of computation.
 R get()
          Get the result.
 R get(long timeout)
          Get the result.
 R get(long timeout, TimeUnit unit)
          Get the result.
 boolean hasValue()
          Check whether the task has produced a value — the status is FINISHED.
 boolean isCanceled()
          Check whether the task has been canceled before completion — the status is CANCELED.
 boolean isCancelled()
          Check whether the task has been canceled before completion — the status is CANCELED.
 boolean isDone()
          Check whether computation has completed — the state is either FINISHED or CANCELED.
 boolean isResolved()
          Returns true if the status is FINISHED and value() will return a result (rather than throwing an exception).
protected  TaskController.RunningState runningState()
          Produce a running state.
 void start()
          Request that the task be run.
protected  void started()
          Called by by the constructor (or a thread spawned by the constructor) when startup is complete.
 TaskController.Status status()
          Get the current status.
protected  void stopped()
          Called by an invocation of doStop() when stopping is complete.
 R value()
          Get the result.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

state

protected final AtomicReference<TaskController.State> state
Current internal state; should only be modified with AtomicReference.compareAndSet(V, V).

Constructor Detail

TaskController

protected TaskController()
Method Detail

status

public TaskController.Status status()
Get the current status.


isDone

public boolean isDone()
Check whether computation has completed — the state is either FINISHED or CANCELED.

Specified by:
isDone in interface Future<R>

hasValue

public boolean hasValue()
Check whether the task has produced a value — the status is FINISHED.


isCanceled

public boolean isCanceled()
Check whether the task has been canceled before completion — the status is CANCELED.


isCancelled

public boolean isCancelled()
Check whether the task has been canceled before completion — the status is CANCELED.

Specified by:
isCancelled in interface Future<R>

isResolved

public boolean isResolved()
Returns true if the status is FINISHED and value() will return a result (rather than throwing an exception).

Specified by:
isResolved in interface ResolvingThunk<R>

start

public void start()
Request that the task be run. If the task is RUNNING or FINISHED, has no effect. There may be a delay between this invocation's return and a state change to RUNNING.

Throws:
CancellationException - If the task is CANCELED.

cancel

public boolean cancel()
Request that the task be abandoned, and that any resources associated with it be disposed. This convenience method sets stopRunning to true.

Returns:
true if the task has not yet finished.

cancel

public boolean cancel(boolean stopRunning)
Request that the task be abandoned, and that any resources associated with it be disposed. PAUSED tasks are always canceled immediately. If stopRunning, a RUNNING task will also be asked to terminate, but there may be a delay between this invocation's return and a state change to CANCELED; and if the task completes successfully in the interim, the cancel request is ignored. (If stopRunning is false, RUNNING tasks are allowed to run to completion.)

Specified by:
cancel in interface Future<R>
Parameters:
stopRunning - Whether a task that has begun running should be canceled.
Returns:
true if the task has not yet started, or if stopRunning is true and the task has not yet finished.

value

public R value()
Get the result. If isDone() is false, ensure that the task is RUNNING and block until it finishes.

Specified by:
value in interface Thunk<R>
Throws:
WrappedException - Wraps any exception encountered, as documented by get(). For simplicity, all exceptions, including RuntimeExceptions, are wrapped.

get

public R get()
      throws InterruptedException,
             ExecutionException
Get the result. If isDone() is false, ensure that the task is RUNNING and block until it finishes.

Specified by:
get in interface Future<R>
Throws:
InterruptedException - If the current thread is interrupted while waiting.
ExecutionException - If the running task terminated early with an exception.
CancellationException - If the final state is CANCELED rather than FINISHED.
RuntimeException - Any other exception that occurs in the controller implementation.

get

public R get(long timeout)
      throws InterruptedException,
             ExecutionException,
             TimeoutException
Get the result. If isDone() is false, ensure that the task is RUNNING and block until it finishes, or until a timeout is reached.

Parameters:
timeout - Maximum wait time, in milliseconds.
Throws:
InterruptedException - If the current thread is interrupted while waiting.
TimeoutException - If the current thread times out while waiting.
ExecutionException - If the running task terminated early with an exception.
CancellationException - If the final state is CANCELED rather than FINISHED.
RuntimeException - Any other exception that occurs in the controller implementation.

get

public R get(long timeout,
             TimeUnit unit)
      throws InterruptedException,
             ExecutionException,
             TimeoutException
Get the result. If isDone() is false, ensure that the task is RUNNING and block until it finishes, or until a timeout is reached.

Specified by:
get in interface Future<R>
Parameters:
timeout - Maximum wait time, in unit units.
unit - Units for timeout.
Throws:
InterruptedException - If the current thread is interrupted while waiting.
TimeoutException - If the current thread times out while waiting.
ExecutionException - If the running task terminated early with an exception.
CancellationException - If the final state is CANCELED rather than FINISHED.
RuntimeException - Any other exception that occurs in the controller implementation.

attemptGet

public Option<R> attemptGet(long timeout)
                     throws ExecutionException
Try to get the result within the given amount of time. If isDone() is false, ensure that the task is RUNNING and block until it finishes, or until a timeout is reached.

Parameters:
timeout - Maximum wait time, in milliseconds.
Returns:
The wrapped result, if it is available before an interrupt or timeout occurs; otherwise, "none".
Throws:
ExecutionException - If the running task terminated early with an exception.
CancellationException - If the final state is CANCELED rather than FINISHED.
RuntimeException - Any other exception that occurs in the controller implementation.

attemptGet

public Option<R> attemptGet(long timeout,
                            TimeUnit unit)
                     throws ExecutionException
Try to get the result within the given amount of time. If isDone() is false, ensure that the task is RUNNING and block until it finishes, or until a timeout is reached.

Parameters:
timeout - Maximum wait time, in unit units.
unit - Units for timeout.
Returns:
The wrapped result, if it is available before an interrupt or timeout occurs; otherwise, "none".
Throws:
ExecutionException - If the running task terminated early with an exception.
CancellationException - If the final state is CANCELED rather than FINISHED.
RuntimeException - Any other exception that occurs in the controller implementation.

finishListeners

public ListenerSet.Sink finishListeners()
Access the ListenerSet responding to the completion of computation. Registered listeners will only be run if the task completes cleanly (without throwing an exception) and the registration occurs before the task completes.


doStart

protected abstract void doStart()
Begin computation and call started(). If starting does not occur immediately (for example, blocking occurs first), the started() call may occur in a different thread.


doStop

protected abstract void doStop()
Terminate computation and call stopped(). Never called before started() has been invoked. If termination does not occur immediately (for example, blocking occurs first), the stopped() call may occur in a different thread.


discard

protected void discard()
Clean up after the task has completed. Called whenever the task enters a canceled or finished state (for example, when finishedCleanly() has been called, or when cancel() is invoked on a PAUSED controller). By default, does nothing, but can be overridden to close connections or throw away unnecessary objects. (Where TaskControllers live far beyond their computation life span (as simple wrappers for a value), this allows objects related to the computation to be garbage-collected in the interim.)


started

protected final void started()
Called by by the constructor (or a thread spawned by the constructor) when startup is complete. Must be invoked before any of the completion methods (stopped(), finishedCleanly(), etc.)


stopped

protected final void stopped()
Called by an invocation of doStop() when stopping is complete. May also be invoked if the task terminates in a canceled-like state, even if stop() was never invoked.


finishedCleanly

protected final void finishedCleanly(R result)
Called when running has completed and produced a value.


finishedWithTaskException

protected final void finishedWithTaskException(Exception e)
Called when the running task terminates early with an exception.


finishedWithImplementationException

protected final void finishedWithImplementationException(RuntimeException e)
Called when the runner implementation encounters an exception.


runningState

protected TaskController.RunningState runningState()
Produce a running state. May be overridden to change the way RunningStates are implemented.