ptolemy.actor.process
Class CompositeProcessDirector

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.actor.Director
              extended by ptolemy.actor.process.ProcessDirector
                  extended by ptolemy.actor.process.CompositeProcessDirector
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Executable, Initializable, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
CSPDirector, DDEDirector, PNDirector, RendezvousDirector

public class CompositeProcessDirector
extends ProcessDirector

A baseclass for directors in process oriented domains that incorporate hierarchical heterogeneity. As with ProcessDirector CompositeProcessDirectors need to keep a count of the number of active processes and the number of processes that are blocked for any reason (e.g., trying to read from an empty channel in PN). CompositeProcessDirector is a subclass of ProcessDirector to facilitate models that consist of non-atomic actors.

A composite process director can be contained by an opaque composite actor that is contained by a composite actor. Ports contained by opaque composite actors are called opaque ports and such ports facilitate data transfer across the composite actor boundaries. A composite process director allocates two branch controllers to monitor data transfer in channels associated with opaque ports. The input branch controller monitors data transfer for channels associated with input opaque ports. The output branch controller monitors data transfer for channels associated with output opaque ports.

Associated with the channels of each opaque port is a pair of process receivers. The producer receiver serves as the channel source and the consumer receiver serves as the channel destination. Each branch controller allocates a branch for each process receiver pair and when executing, a branch repeatedly attempts to transfer a single token from its producer receiver to its consumer receiver.

When a branch blocks while attempting to transfer data, it informs its branch controller by passing the branch controller the blocked receiver. If all of the branches of a controller have blocked, then we say that the branch controller is blocked and the branch controller informs the composite process director. In addition to monitoring the status of its branch controllers, a composite process director keeps track of the state of the actors that it contains. Actors can be internally or externally blocked. We say that an actor is externally blocked if it is blocked waiting to transfer tokens to or from a boundary port of its container actor. Actors that are blocked but not externally are said to be internally blocked.

Composite process directors monitor the state of the branch controllers and contained actors and when necessary invoke the _resolveDeadlock() method to deal with deadlocks. In the remainder of this paragraph we consider the case of a process-oriented opaque composite actor that is contained by another process-oriented opaque composite actor. If the actors contained by the inner composite actor are not blocked, then execution of the inner composite actor is allowed to continue independent of the state of the branch controllers. If the actors contained by the inner composite actor are internally blocked, then after the branch controllers have been deactivated, execution of the composite actor ends and postfire returns false indicating that successive iterations are not allowed. If the actors contained by the inner composite actor are externally blocked, then the composite process director waits until the branch controllers block (an inevitable condition) and registers the block with the containing (outer) composite director of the actor.

In this paragraph we consider the case of a process-oriented opaque composite actor that is contained by a schedule-oriented (non process) opaque composite actor. If the actors contained by the inner composite actor are not blocked, then execution of the inner composite actor is allowed to continue independent of the state of the branch controllers. If the actors contained by the inner composite actor are internally blocked, then after the branch controllers have been deactivated, execution of the composite actor ends and postfire returns false indicating that successive iterations are not allowed. If the actors contained by the inner composite actor are externally blocked, then the composite process director waits until the branch controllers block (an inevitable condition) and ends the iteration with postfire() returning true indicating that successive iterations are allowed.

Since:
Ptolemy II 1.0
Version:
$Id: CompositeProcessDirector.java 57040 2010-01-27 20:52:32Z cxh $
Author:
John S. Davis II
See Also:
Director, Serialized Form
Accepted Rating:
Yellow (davisj)
Proposed Rating:
Green (mudit)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  java.util.HashSet _blockedReceivers
           
private  java.lang.Object _branchControllerLock
           
private  BranchController _inputBranchController
          The controller that handles inputs to the composite.
private  boolean _inputControllerIsBlocked
           
private  boolean _onFirstIteration
          Flag indicating whether we have executed the first iteration.
private  BranchController _outputBranchController
          The controller that handles outputs from the composite.
private  boolean _outputControllerIsBlocked
           
 
Fields inherited from class ptolemy.actor.process.ProcessDirector
_notDone, _stopFireRequested
 
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
CompositeProcessDirector()
          Construct a director in the default workspace with an empty string as its name.
CompositeProcessDirector(CompositeEntity container, java.lang.String name)
          Construct a director in the given container with the given name.
CompositeProcessDirector(Workspace workspace)
          Construct a director in the workspace with an empty name.
 
Method Summary
protected  boolean _areActorsExternallyBlocked()
          Return true if one or more contained actor is externally blocked; return false otherwise.
protected  boolean _areThreadsDeadlocked()
          Return false if the number of blocked processes is less than the number of active actors; return true otherwise.
protected  void _controllerBlocked(BranchController controller)
          Register that the specified controller is blocked.
protected  void _controllerUnBlocked(BranchController controller)
          Unregister the specified controller as being no longer blocked.
protected  boolean _isInputControllerBlocked()
          Return true if the input controller of this director is blocked; return false otherwise.
protected  boolean _isOutputControllerBlocked()
          Return true if the output controller of this director is blocked; return false otherwise.
protected  boolean _resolveDeadlock()
          Attempt to resolve a deadlock and return true if the deadlock no longer exists and successive iterations are allowed; if the deadlock still exists then return false indicating that future iterations are not allowed.
protected  boolean _resolveInternalDeadlock()
          Return false indicating that resolution of an internal deadlock was unsuccessful and execution should discontinue.
 java.lang.Object clone(Workspace workspace)
          Clone the director into the specified workspace.
 void createBranchController(java.util.Iterator ports)
          Create a input and/or output branch controllers according to whether the ports passed in as arguments are input or output ports.
 BranchController getInputController()
          Return the input branch controller of this director.
 BranchController getOutputController()
          Return the output branch controller of this director.
 void initialize()
          Invoke the initialize() methods of all the deeply contained actors in the container (a composite actor) of this director.
 Receiver newReceiver()
          Return a new receiver of a type compatible with this director.
 boolean prefire()
          If there are input or output ports, and this is the first iteration, then start threads to handle the inputs and outputs.
 void setModelTime(Time newTime)
          Set a new value to the current time of the model, where the new time can be earlier than the current time.
 void stopInputBranchController()
          Stop the input branch controller of this director.
 void stopOutputBranchController()
          Stop the output branch controller of this director.
 void threadBlocked(java.lang.Thread thread, ProcessReceiver receiver)
          Notify the director that the specified thread is blocked on an I/O operation.
 void threadUnblocked(java.lang.Thread thread, ProcessReceiver receiver)
          Notify the director that the specified thread is unblocked on an I/O operation.
 void wrapup()
          End the execution of the model under the control of this director.
 
Methods inherited from class ptolemy.actor.process.ProcessDirector
_areAllThreadsStopped, _getActiveThreadsCount, _getBlockedThreadsCount, _getStoppedThreadsCount, _newProcessThread, addThread, finish, fire, initialize, isStopFireRequested, isStopRequested, isThreadActive, postfire, preinitialize, removeThread, stop, stopFire, terminate, threadHasPaused, threadHasResumed, transferInputs, transferOutputs
 
Methods inherited from class ptolemy.actor.Director
_description, _fireContainerAt, _isEmbedded, _isTopLevel, _transferInputs, _transferOutputs, addInitializable, attributeChanged, createSchedule, defaultDependency, fireAt, fireAt, fireAtCurrentTime, getCausalityInterface, getCurrentTime, getErrorTolerance, getGlobalTime, getModelNextIterationTime, getModelStartTime, getModelStopTime, getModelTime, getNextIterationTime, getStartTime, getStopTime, getTimeResolution, implementsStrictActorSemantics, invalidateResolvedTypes, invalidateSchedule, isFireFunctional, isStrict, iterate, preinitialize, removeInitializable, requestInitialization, setContainer, setCurrentTime, suggestedModalModelDirectors, supportMultirateFiring
 
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

_onFirstIteration

private boolean _onFirstIteration
Flag indicating whether we have executed the first iteration.


_inputBranchController

private BranchController _inputBranchController
The controller that handles inputs to the composite.


_outputBranchController

private BranchController _outputBranchController
The controller that handles outputs from the composite.


_inputControllerIsBlocked

private volatile boolean _inputControllerIsBlocked

_outputControllerIsBlocked

private volatile boolean _outputControllerIsBlocked

_blockedReceivers

private java.util.HashSet _blockedReceivers

_branchControllerLock

private java.lang.Object _branchControllerLock
Constructor Detail

CompositeProcessDirector

public CompositeProcessDirector()
Construct a director in the default workspace with an empty string as its name. The director is added to the list of objects in the workspace. Increment the version number of the workspace.


CompositeProcessDirector

public CompositeProcessDirector(Workspace workspace)
Construct a director in the workspace with an empty name. The director is added to the list of objects in the workspace. Increment the version number of the workspace.

Parameters:
workspace - The workspace of this object.

CompositeProcessDirector

public CompositeProcessDirector(CompositeEntity container,
                                java.lang.String name)
                         throws IllegalActionException,
                                NameDuplicationException
Construct a director in the given container with the given name. If the container argument must not be null, or a NullPointerException will be thrown. If the name argument is null, then the name is set to the empty string. Increment the version number of the workspace.

Parameters:
container - The container.
name - Name of this director.
Throws:
IllegalActionException - If the name contains a period, or if the director is not compatible with the specified container.
NameDuplicationException - If the container not a CompositeActor and the name collides with an entity in the container.
Method Detail

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone the director into the specified workspace. The new object is not added to the directory of that workspace (It must be added by the user if he wants it to be there). The result is a new director with no container, no pending mutations, and no topology listeners. The count of active processes is zero.

Overrides:
clone in class ProcessDirector
Parameters:
workspace - The workspace for the cloned object.
Returns:
The new ProcessDirector.
Throws:
java.lang.CloneNotSupportedException - If one of the attributes cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

createBranchController

public void createBranchController(java.util.Iterator ports)
                            throws IllegalActionException
Create a input and/or output branch controllers according to whether the ports passed in as arguments are input or output ports. If any of the ports are input (output) ports, then they will be added to the input (output) branch controller.

Parameters:
ports - The ports for which branches will be assigned.
Throws:
IllegalActionException - If any of the ports are not opaque.

getInputController

public BranchController getInputController()
Return the input branch controller of this director. If this method is called prior to the invocation of initialize(), then this method will return null.

Returns:
The input branch controller of this director.

getOutputController

public BranchController getOutputController()
Return the output branch controller of this director. If this method is called prior to the invocation of initialize(), then this method will return null.

Returns:
The output branch controller of this director.

initialize

public void initialize()
                throws IllegalActionException
Invoke the initialize() methods of all the deeply contained actors in the container (a composite actor) of this director. These are expected to call initialize(Actor), which will result in the creation of a new thread for each actor. Also, set current time to 0.0, or to the current time of the executive director of the container, if there is one.

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

newReceiver

public Receiver newReceiver()
Return a new receiver of a type compatible with this director. In this base class, this returns an instance of MailboxBoundaryReceiver.

Overrides:
newReceiver in class ProcessDirector
Returns:
A new MailboxBoundaryReceiver.

prefire

public boolean prefire()
                throws IllegalActionException
If there are input or output ports, and this is the first iteration, then start threads to handle the inputs and outputs.

Specified by:
prefire in interface Executable
Overrides:
prefire in class ProcessDirector
Returns:
True.
Throws:
IllegalActionException - If a derived class throws it.

setModelTime

public void setModelTime(Time newTime)
                  throws IllegalActionException
Set a new value to the current time of the model, where the new time can be earlier than the current time. This overrides the setCurrentTime() in the Director base class. The new time may be earlier than the current time.

Overrides:
setModelTime in class Director
Parameters:
newTime - The new current simulation time.
Throws:
IllegalActionException - Not thrown in this base class.
See Also:
Director.getModelTime()

stopInputBranchController

public void stopInputBranchController()
Stop the input branch controller of this director. This method will block until the input branch controller has stopped due to all of the branches it controls stopping, or until the calling thread is interrupted.


stopOutputBranchController

public void stopOutputBranchController()
Stop the output branch controller of this director. This method will block until the output branch controller has stopped due to all of the branches it controls stopping.


threadBlocked

public void threadBlocked(java.lang.Thread thread,
                          ProcessReceiver receiver)
Notify the director that the specified thread is blocked on an I/O operation. If the thread has not been registered with addThread(), then this call is ignored. This overrides the base class to keep track of the receiver in case it is on the boundary of the containing composite actor.

Overrides:
threadBlocked in class ProcessDirector
Parameters:
thread - The thread.
receiver - The receiver handling the I/O operation, or null if it is not a specific receiver.
See Also:
ProcessDirector.addThread(Thread)

threadUnblocked

public void threadUnblocked(java.lang.Thread thread,
                            ProcessReceiver receiver)
Notify the director that the specified thread is unblocked on an I/O operation. If the thread has not been registered with threadBlocked(), then this call is ignored. This overrides the base class to keep track of the receiver in case it is on the boundary of the containing composite actor.

Overrides:
threadUnblocked in class ProcessDirector
Parameters:
thread - The thread.
receiver - The receiver handling the I/O operation, or null if it is not a specific receiver.
See Also:
*

wrapup

public void wrapup()
            throws IllegalActionException
End the execution of the model under the control of this director. A flag is set in all of the receivers that causes each process to terminate at the earliest communication point.

Prior to setting receiver flags, this method wakes up the threads if they all are stopped.

This method is not synchronized on the workspace, so the caller should be.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class ProcessDirector
Throws:
IllegalActionException - If an error occurs while accessing the receivers of all actors under the control of this director.

_areActorsExternallyBlocked

protected boolean _areActorsExternallyBlocked()
                                       throws InvalidStateException,
                                              IllegalActionException
Return true if one or more contained actor is externally blocked; return false otherwise. We say an actor is externally blocked if it is blocked attempting data transfer through a boundary port of its containing actor. Note that a true return value for this method does not imply that the contained actors are deadlocked.

Returns:
true If one or more contained actors are externally blocked; return false otherwise.
Throws:
IllegalActionException
InvalidStateException

_areThreadsDeadlocked

protected boolean _areThreadsDeadlocked()
Return false if the number of blocked processes is less than the number of active actors; return true otherwise. Note that if the number of active actors is 0 then this method will return true. Derived classes may override this method to add domain specific functionality. Implementations of this method must be synchronized.

Overrides:
_areThreadsDeadlocked in class ProcessDirector
Returns:
false If the number of blocked processes is less than the number of active actors; return true otherwise.

_controllerBlocked

protected void _controllerBlocked(BranchController controller)
Register that the specified controller is blocked. Pass the specified controller in as an argument. Note that if the controller passed in as an argument is not contained by this director or if the state of the controller is not blocked then no registration operation will be performed by this method.

Parameters:
controller - The controller for which registration of a blocked state will occur.

_controllerUnBlocked

protected void _controllerUnBlocked(BranchController controller)
Unregister the specified controller as being no longer blocked. Pass the specified controller in as an argument. Note that if the controller passed in as an argument is not contained by this director or if the state of the controller is blocked then no registration operation will be performed by this method.

Parameters:
controller - The controller for which registration of an unblocked state will occur.

_isInputControllerBlocked

protected boolean _isInputControllerBlocked()
Return true if the input controller of this director is blocked; return false otherwise.

Returns:
true If the input controller of this director is blocked; return false otherwise.

_isOutputControllerBlocked

protected boolean _isOutputControllerBlocked()
Return true if the output controller of this director is blocked; return false otherwise.

Returns:
true If the output controller of this director is blocked; return false otherwise.

_resolveDeadlock

protected boolean _resolveDeadlock()
                            throws IllegalActionException
Attempt to resolve a deadlock and return true if the deadlock no longer exists and successive iterations are allowed; if the deadlock still exists then return false indicating that future iterations are not allowed. If the deadlock is internal then apply a domain specific algorithm to attempt deadlock resolution via the _resolveInternalDeadlock() method. If the algorithm is successful and deadlock no longer exists then return true. If the algorithm is unsuccessful and deadlock persists then end the iteration and return false.

If the deadlock is an external deadlock and the containing model of computation is process-oriented, then register the externally blocked receivers with the composite actor that contains this director's composite actor. If the deadlock is an external deadlock and the containing model of computation is schedule-oriented, then end this iteration and return true.

While in special cases it my be useful to override this method for domain specific functionality it is more likely that this method will remain the same and the _resolveInternalDeadlock() method will be overridden for particular models of computation.

Overrides:
_resolveDeadlock in class ProcessDirector
Returns:
false If deadlock could not be resolved and successive iterations are not allowed; return true otherwise.
Throws:
IllegalActionException - Not thrown in this base class.

_resolveInternalDeadlock

protected boolean _resolveInternalDeadlock()
                                    throws IllegalActionException
Return false indicating that resolution of an internal deadlock was unsuccessful and execution should discontinue. Subclasses may override this method for domain specific functionality. Domain specific functionality should include algorithms to resolve internal deadlock. Successful application of the algorithm should result in a return value of true; unsuccessful application should result in a return value of false.

Returns:
False indicating that internal deadlock was not resolved.
Throws:
IllegalActionException - Not thrown in this base class.