ptolemy.actor.lib.hoc
Class ThreadedComposite.ThreadedDirector

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.actor.Director
              extended by ptolemy.actor.lib.hoc.ThreadedComposite.ThreadedDirector
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Executable, Initializable, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Enclosing class:
ThreadedComposite

private class ThreadedComposite.ThreadedDirector
extends Director

A specialized director that fires a contained actor in a separate thread. The prefire() method returns true if the inside thread is alive. The fire() method posts input events, if any, for the current firing on a queue for the inside thread to consume. If the firing is in response to a prior refiring request by this director, then the fire() method will also wait for the inside thread to complete its firing, and will then produce outputs from that firing. The postfire() method posts a request to postfire the contained actor and also requests a refiring of this director at the current time plus the delay value (unless the delay value is UNDEFINED). The wrapup() method requests termination of the inside thread. If postfire() of the contained actor returns false, then postfire() of this director will return false, requesting a halt to execution of the model.


Nested Class Summary
private  class ThreadedComposite.ThreadedDirector.CompositeThread
          The inside thread, which executes the contained actor.
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  java.lang.Throwable _exception
          If an exception occurs in the inside thread, the exception will be assigned to this member, which will cause the the next invocation of the fire() or wrapup() method to throw the exception.
private  java.util.Set<Time> _fireAtTimes
          Record of the times which refire requests have been made and not yet processed by any of the fireAt() methods.
private  java.util.concurrent.LinkedBlockingQueue<ThreadedComposite.TokenFrame> _inputFrames
          Queue of unprocessed input events.
private  java.util.List<ThreadedComposite.QueuedToken> _inputTokens
          List of input events in the current iteration.
private  java.util.LinkedList<ThreadedComposite.TokenFrame> _outputFrames
          Queue of unprocessed output events.
private  java.util.Queue<Time> _outputTimes
          Record of the time stamps at which to produce outputs.
private  boolean _synchronizeToRealTime
          The value of the synchronizeToRealTime parameter when initialize() was invoked.
private  java.lang.Thread _thread
          The thread that executes the contained actors.
 
Fields inherited from class ptolemy.actor.Director
_actorsFinishedExecution, _currentTime, _finishRequested, _initializables, _stopRequested, timeResolution
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
ThreadedComposite.ThreadedDirector(CompositeEntity container, java.lang.String name)
          Create a new instance of the director for ThreadedComposite.
 
Method Summary
 java.lang.Object clone(Workspace workspace)
          Clone the director into the specified workspace.
 void fire()
          Produce outputs (if appropriate).
 Time fireAt(Actor actor, Time time)
          Delegate by calling fireAt() on the director of the container's container (the executive director), and make a local record that a refiring request has been made for the specified time.
 Time getModelTime()
          Return the current time, which is the most recent input frame processed (or being processed) by the inside thread.
 void initialize()
          Start the inside thread.
 Receiver newReceiver()
          Return a new instance of QueueReceiver.
 boolean postfire()
          Consume inputs (if any) and post a frame on the queue for the inside thread to consume.
 boolean prefire()
          Return true if the inside thread is alive.
 void stop()
          Override the base class to post a "stop frame" on the queue for the inside thread to stop.
 boolean transferInputs(IOPort port)
          Record data from the specified input port for transfer to the queue used to communicate these data to the inside thread.
 boolean transferOutputs(IOPort port)
          Override the base class to do nothing since the fire() method of this director directly handles producing the outputs.
 void wrapup()
          Override the base class to wait until the inside thread terminates and then call super.wrapup().
 
Methods inherited from class ptolemy.actor.Director
_description, _fireContainerAt, _isEmbedded, _isTopLevel, _transferInputs, _transferOutputs, addInitializable, attributeChanged, createSchedule, defaultDependency, finish, fireAt, fireAtCurrentTime, getCausalityInterface, getCurrentTime, getErrorTolerance, getGlobalTime, getModelNextIterationTime, getModelStartTime, getModelStopTime, getNextIterationTime, getStartTime, getStopTime, getTimeResolution, implementsStrictActorSemantics, initialize, invalidateResolvedTypes, invalidateSchedule, isFireFunctional, isStopRequested, isStrict, iterate, preinitialize, preinitialize, removeInitializable, requestInitialization, setContainer, setCurrentTime, setModelTime, stopFire, suggestedModalModelDirectors, supportMultirateFiring, terminate
 
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, _propagateExistence, getContainer, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, setName, updateContent
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _exportMoMLContents, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, attributeList, attributeList, attributeTypeChanged, clone, containedObjectsIterator, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getElementName, getFullName, getModelErrorHandler, getName, getName, getPrototypeList, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateExistence, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, uniqueName, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

_exception

private java.lang.Throwable _exception
If an exception occurs in the inside thread, the exception will be assigned to this member, which will cause the the next invocation of the fire() or wrapup() method to throw the exception.


_fireAtTimes

private java.util.Set<Time> _fireAtTimes
Record of the times which refire requests have been made and not yet processed by any of the fireAt() methods. This set is accessed from both the director thread and the inside thread so it has to be thread safe.


_inputFrames

private java.util.concurrent.LinkedBlockingQueue<ThreadedComposite.TokenFrame> _inputFrames
Queue of unprocessed input events. This is a blocking queue, which blocks the calling thread if the queue is empty. This is accessed by both the director thread and the inside thread, so it has to be thread safe (LinkedBlockingQueue is a thread-safe container).


_inputTokens

private java.util.List<ThreadedComposite.QueuedToken> _inputTokens
List of input events in the current iteration. This is accessed only in the director thread so it need not be thread safe.


_outputFrames

private java.util.LinkedList<ThreadedComposite.TokenFrame> _outputFrames
Queue of unprocessed output events. This queue is accessed from multiple threads, so it must be thread safe.


_outputTimes

private java.util.Queue<Time> _outputTimes
Record of the time stamps at which to produce outputs. These are enqueued and dequeued in time stamp order. If the delay value is UNDEFINED, then this is accessed from the inside thread as well as the director thread, so it needs to be thread safe. To ensure this, we always access it within a block synchronized on this director.


_synchronizeToRealTime

private boolean _synchronizeToRealTime
The value of the synchronizeToRealTime parameter when initialize() was invoked.


_thread

private java.lang.Thread _thread
The thread that executes the contained actors.

Constructor Detail

ThreadedComposite.ThreadedDirector

public ThreadedComposite.ThreadedDirector(CompositeEntity container,
                                          java.lang.String name)
                                   throws IllegalActionException,
                                          NameDuplicationException
Create a new instance of the director for ThreadedComposite.

Parameters:
container - The container for the director.
name - The name of the director.
Throws:
IllegalActionException - Not thrown in this base class.
NameDuplicationException - Not thrown in this base class.
Method Detail

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone the director into the specified workspace.

Overrides:
clone in class Attribute
Parameters:
workspace - The workspace for the new object.
Returns:
A new director.
Throws:
java.lang.CloneNotSupportedException - If a derived class has has an attribute that cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

fire

public void fire()
          throws IllegalActionException
Produce outputs (if appropriate).

Specified by:
fire in interface Executable
Overrides:
fire in class Director
Throws:
IllegalActionException - If production of an output fails (e.g. type error), or if this thread is interrupted while we are waiting for output to produce.

fireAt

public Time fireAt(Actor actor,
                   Time time)
            throws IllegalActionException
Delegate by calling fireAt() on the director of the container's container (the executive director), and make a local record that a refiring request has been made for the specified time. Note that the executive director may modify the requested time. If it does, the modified value is returned. It is up to the calling actor to throw an exception if the modified time is not acceptable.

Overrides:
fireAt in class Director
Parameters:
actor - The actor requesting firing.
time - The time at which to fire.
Returns:
The time at which the actor passed as an argument will be fired.
Throws:
IllegalActionException - If the executive director throws it.
See Also:
Director.fireAtCurrentTime(Actor)

getModelTime

public Time getModelTime()
Return the current time, which is the most recent input frame processed (or being processed) by the inside thread.

Overrides:
getModelTime in class Director
Returns:
The current time.
See Also:
Director.setModelTime(Time)

initialize

public void initialize()
                throws IllegalActionException
Start the inside thread.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class Director
Throws:
IllegalActionException - If the initialize() method of one of the inside actors throws it.

newReceiver

public Receiver newReceiver()
Return a new instance of QueueReceiver.

Overrides:
newReceiver in class Director
Returns:
A new instance of QueueReceiver.
See Also:
QueueReceiver

prefire

public boolean prefire()
                throws IllegalActionException
Return true if the inside thread is alive.

Specified by:
prefire in interface Executable
Overrides:
prefire in class Director
Returns:
True if the inside thread is still alive.
Throws:
IllegalActionException - Not thrown in this base class.

postfire

public boolean postfire()
                 throws IllegalActionException
Consume inputs (if any) and post a frame on the queue for the inside thread to consume. A frame will be posted even if there are no inputs if a refiring request has been made for the current time.

Specified by:
postfire in interface Executable
Overrides:
postfire in class Director
Returns:
True if the inside thread is still alive.
Throws:
IllegalActionException - Not thrown in this base class.

stop

public void stop()
Override the base class to post a "stop frame" on the queue for the inside thread to stop.

Specified by:
stop in interface Executable
Overrides:
stop in class Director

transferInputs

public boolean transferInputs(IOPort port)
                       throws IllegalActionException
Record data from the specified input port for transfer to the queue used to communicate these data to the inside thread. This is called in the fire() method of the enclosing composite actor after the prefire() method of this director has been called and before its fire() method is called.

Overrides:
transferInputs in class Director
Parameters:
port - The port to transfer tokens from.
Returns:
True if at least one data token is transferred.
Throws:
IllegalActionException - If reading the inputs fails.

transferOutputs

public boolean transferOutputs(IOPort port)
                        throws IllegalActionException
Override the base class to do nothing since the fire() method of this director directly handles producing the outputs. In particular, we don't want to read from the inside of the output ports because the inside thread may be concurrently writing to them for the next iteration.

Overrides:
transferOutputs in class Director
Parameters:
port - The port to transfer tokens from.
Returns:
False, indicating that no data token is produced now.
Throws:
IllegalActionException - If writing the outputs fails.

wrapup

public void wrapup()
            throws IllegalActionException
Override the base class to wait until the inside thread terminates and then call super.wrapup().

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class Director
Throws:
IllegalActionException - If the wrapup() method of one of the associated actors throws it.