Package ptolemy.actor

Class Manager

  • All Implemented Interfaces:
    java.lang.Cloneable, java.lang.Runnable, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

    public class Manager
    extends NamedObj
    implements java.lang.Runnable
    A Manager governs the execution of a model in a domain-independent way. Its methods are designed to be called by a GUI, an applet, a command-line interface, or the top-level code of an application. The manager can execute the model in the calling thread or in a separate thread. The latter is useful when the caller wishes to remain live during the execution of the model.

    There are three methods that can be used to start execution of a system attached to the manager. The execute() method is the most basic way to execute a model. The model will be executed synchronously, meaning that the execute() method will return when execution has completed. Any exceptions that occur will be thrown by the execute method to the calling thread, and will not be reported to any execution listeners. The run() method also initiates synchronous execution of a model, but additionally catches all exceptions and passes them to the notifyListenersOfException() method without throwing them to the calling thread. The startRun() method, unlike the previous two techniques, begins asynchronous execution of a model. This method starts a new thread for execution of the model and then returns immediately. Exceptions are reported using the notifyListenersOfException() method.

    In addition, execution can be manually driven, one phase at a time, using the methods initialize(), iterate() and wrapup(). This is most useful for testing purposes. For example, a type system check only needs to get the resolved types, which are found during initialize, so the test can avoid actually executing the system. Also, when testing mutations, the model can be examined after each toplevel iteration to ensure the proper behavior.

    A manager provides services for cleanly handling changes to the topology. These include such changes as adding or removing an entity, port, or relation, creating or destroying a link, and changing the value or type of a parameter. Collectively, such changes are called mutations. Usually, mutations cannot safely occur at arbitrary points in the execution of a model. Models can queue mutations with any object in the hierarchy or with the manager using the requestChange() method. An object in the hierarchy simply delegates the request to its container, so the request propagates up the hierarchy until it gets to the top level composite actor, which delegates to the manager, which performs the change at the earliest opportunity. In this implementation of Manager, the changes are executed between iterations.

    A service is also provided whereby an object can be registered with the composite actor as a change listener. A change listener is informed when mutations that are requested via requestChange() are executed successfully, or when they fail with an exception.

    Manager can optimize the performance of an execution by making the workspace write protected during an iteration, if all relevant directors permit this. This removes some of the overhead of obtaining read and write permission on the workspace. By default, directors do not permit this, but many directors explicitly relinquish write access to allow faster execution. Such directors are declaring that they will not make changes to the topology during execution. Instead, any desired mutations are delegated to the manager via the requestChange() method.

    Many domains make use of static analyses for performing, e.g., static scheduling of actor firings. In some cases, these analyses must make use of global information. The class provides a centralized mechanism for managing such global analyses. During preinitialize, domains can invoke the getAnalysis and addAnalysis methods to create a global analysis. It is up to the users of this mechanism to ensure that a particular type of analysis is only created once, if that is what is required. After preinitialize, the manager clears the list of analyses, to avoid unnecessary memory usage, and to ensure that the analyses are performed again on the next invocation of the model. This is somewhat preferable to tying a cache of analysis information to the version of the workspace, since the version number of the workspace itself may change during preinitialize as domains add annotation to the model.

    Since:
    Ptolemy II 0.2
    Version:
    $Id$
    Author:
    Steve Neuendorffer, Lukito Muliadi, Edward A. Lee, Elaine Cheong, Contributor: Mudit Goel, John S. Davis II, Bert Rodiers, Daniel Crawl
    Pt.AcceptedRating:
    Yellow (cxh)
    Pt.ProposedRating:
    Green (neuendor)
    • Field Detail

      • CORRUPTED

        public static final Manager.State CORRUPTED
        Indicator that the model may be corrupted.
      • IDLE

        public static final Manager.State IDLE
        Indicator that there is no currently active execution.
      • INFERING_WIDTHS

        public static final Manager.State INFERING_WIDTHS
        Indicator that width inference is being done.
      • INITIALIZING

        public static final Manager.State INITIALIZING
        Indicator that the execution is in the initialize phase.
      • ITERATING

        public static final Manager.State ITERATING
        Indicator that the execution is in an iteration.
      • PAUSED

        public static final Manager.State PAUSED
        Indicator that the execution is paused.
      • PAUSED_ON_BREAKPOINT

        public static final Manager.State PAUSED_ON_BREAKPOINT
        Indicator that the execution is paused on a breakpoint.
      • PREINITIALIZING

        public static final Manager.State PREINITIALIZING
        Indicator that the execution is in the preinitialize phase.
      • RESOLVING_TYPES

        public static final Manager.State RESOLVING_TYPES
        Indicator that type resolution is being done.
      • THROWING_A_THROWABLE

        public static final Manager.State THROWING_A_THROWABLE
        Indicator that the execution is throwing a throwable.
      • WRAPPING_UP

        public static final Manager.State WRAPPING_UP
        Indicator that the execution is in the wrapup phase.
      • EXITING

        public static final Manager.State EXITING
        Indicator that the execution is in the wrapup phase and about to exit.
      • minimumStatisticsTime

        public static int minimumStatisticsTime
        The minimum amount of time that may elapse during certain operations before statistics are generated. The Manager and other classes in Ptolemy will print out statistics if the amount of time (in milliseconds) named by this variable elapses during certain steps such as preinitialize(). The initial default value is 10000, meaning that certain operations can take up to 10 seconds before statistics are printed.
        See Also:
        CompositeEntity.statistics(String)
      • SHUTDOWN_TIME

        public static long SHUTDOWN_TIME
        The amount of time to allow for the model to terminate gracefully before shutting it down when the JVM is shut down due to control-C, user logging out, etc.
    • Constructor Detail

      • Manager

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

        public Manager​(java.lang.String name)
                throws IllegalActionException
        Construct a manager in the default workspace with the given name. If the name argument is null, then the name is set to the empty string. The manager is added to the list of objects in the workspace. Increment the version number of the workspace.
        Parameters:
        name - Name of this Manager.
        Throws:
        IllegalActionException - If the name has a period.
      • Manager

        public Manager​(Workspace workspace,
                       java.lang.String name)
                throws IllegalActionException
        Construct a manager in the given workspace with the given name. If the workspace argument is null, use the default workspace. The manager is added to the list of objects in the workspace. If the name argument is null, then the name is set to the empty string. Increment the version number of the workspace.
        Parameters:
        workspace - Object for synchronization and version tracking.
        name - Name of this Manager.
        Throws:
        IllegalActionException - If the name has a period.
    • Method Detail

      • addAnalysis

        public void addAnalysis​(java.lang.String name,
                                java.lang.Object analysis)
        Add a static analysis to this manager. A static analysis is simply an object that is recorded in a hash table and cleared at the end of preinitialize(), with no semantics associated with that object. The intent is for that object to serve as a repository for static analysis results, but clearing it and the end of preinitialize isn't quite right. The idea is that it is cleared at a point when the analysis has to be redone after that point. But doing this at the end of preinitialize means this won't work with models that mutate either during preinitialize() (as in higher- order actors) or during execution.
        Parameters:
        name - The name of the analysis.
        analysis - The analysis to record.
        See Also:
        getAnalysis(String)
      • addExecutionListener

        public void addExecutionListener​(ExecutionListener listener)
        Add a listener to be notified when the model execution changes state. If the specified listener is already a listener, do nothing.
        Parameters:
        listener - The listener.
        See Also:
        removeExecutionListener(ExecutionListener)
      • elapsedTimeSinceStart

        public long elapsedTimeSinceStart()
        Return the elapsed time (in milliseconds) since the start of execution of the model. The start of execution is defined to be the time after initialize() has been called and before any component has been iterated.
        Returns:
        The time in milliseconds since the start of execution of the model.
      • enablePrintTimeAndMemory

        public void enablePrintTimeAndMemory​(boolean enabled)
        Enable or disable printing time and memory usage at the end of model execution.
        Parameters:
        enabled - Whether time and memory printing is enabled.
      • execute

        public void execute()
                     throws KernelException,
                            IllegalActionException
        Execute the model. Begin with the initialization phase, followed by a sequence of iterations, followed by a wrapup phase. The sequence of iterations concludes when the postfire() method of the container (the top-level composite actor) returns false, or when the finish() method is called.

        The execution is performed in the calling thread (the current thread), so this method returns only after execution finishes. If you wish to perform execution in a new thread, use startRun() instead. Even if an exception occurs during the execution, the wrapup() method is called (in a finally clause).

        If an exception occurs during the execution, delegate to the exception handlers (if there are any) to handle these exceptions. If there are no exception handlers, it is up to the caller to handle (e.g. report) the exception. If you do not wish to handle exceptions, but want to execute within the calling thread, use run().

        Throws:
        KernelException - If the model throws it.
        IllegalActionException - If the model is already running, or if there is no container.
        See Also:
        run()
      • exitAfterWrapup

        public void exitAfterWrapup()
        Cause the system to exit after wrapup(). If the ptolemy.ptII.exitAfterWrapup property is not set, then when wrapup() is almost finished, we call System.exit(). If the ptolemy.ptII.exitAfterWrapup property is set, then we throw an Exception.
      • finish

        public void finish()
        If the state is not IDLE, set a flag to request that execution stop and exit in a completely deterministic fashion at the end of the next toplevel iteration. This method may be called from within an actor to stop the execution of the model. This will result in stop() being called on the top level CompositeActor, although not necessarily immediately. Note that this method is allowed to be called if the model is paused and actors that implement the stop() method must properly respond to that method even if the model is paused.
        See Also:
        Executable.stop()
      • getAnalysis

        public java.lang.Object getAnalysis​(java.lang.String name)
        Get the analysis with the given name, or return null if no such analysis exists.
        Parameters:
        name - The name of the analysis.
        Returns:
        the analysis with the given name, or null.
        See Also:
        addAnalysis(String, Object)
      • getRealStartTime

        public long getRealStartTime()
        Get the real time at which the model began executing.
        Returns:
        The real time at which the model began executing.
      • getContainer

        public NamedObj getContainer()
        Return the top-level composite actor for which this manager controls execution.
        Specified by:
        getContainer in interface Nameable
        Overrides:
        getContainer in class NamedObj
        Returns:
        The composite actor that this manager is responsible for.
      • getIterationCount

        public int getIterationCount()
        Return the iteration count, which is the number of iterations that have been started (but not necessarily completed).
        Returns:
        The number of iterations started.
      • getPreinitializeVersion

        public long getPreinitializeVersion()
        Return the workspace version on the last completion of preinitializeAndResolveTypes(). This can be used to optimize away actions on repeated runs when the workspace hasn't changed between runs.
        Returns:
        the workspace version on the last completion of preinitializeAndResolveTypes().
      • getState

        public Manager.State getState()
        Return the current state of execution of the manager.
        Returns:
        The state of execution.
      • getStatusMessage

        public java.lang.String getStatusMessage()
        Return any messages, such as the amount of time consumed. This method is called to update the status bar, so the output should be short.
        Returns:
        the message
        See Also:
        setStatusMessage(String)
      • getExecutionIdentifier

        public java.lang.Object getExecutionIdentifier​(java.lang.Throwable throwable)
        Get the execution identifier object for a throwable.

        An execution identifier is an object given to the Manager via setExecutionIdentifier(), and cleared during preinitialize(). If the Manager notifies a listener of a model error, getExecutionIdentifier() can be used to map that error back to the executionIdentifier object.

        Parameters:
        throwable - The throwable.
        Returns:
        The execution identifier object if one was set, otherwise null.
        See Also:
        setExecutionIdentifier(Object)
      • getWaitingThread

        public java.lang.Thread getWaitingThread()
        Return a thread that is waiting and can be interrupted in the event that a change request is made, or null to indicate that there is no thread waiting.
        Returns:
        The thread that is waiting, or null to indicate that no thread is waiting.
        See Also:
        setWaitingThread(Thread)
      • initialize

        public void initialize()
                        throws KernelException,
                               IllegalActionException
        Initialize the model. This calls the preinitialize() method of the container, followed by the resolveTypes() and initialize() methods. Set the Manager's state to PREINITIALIZING and INITIALIZING as appropriate. This method is read synchronized on the workspace.
        Throws:
        KernelException - If the model throws it.
        IllegalActionException - If the model is already running, or if there is no container.
      • invalidateResolvedTypes

        public void invalidateResolvedTypes()
        Indicate that resolved types in the system may no longer be valid. This will force type resolution to be redone on the next iteration.
      • isExitingAfterWrapup

        public boolean isExitingAfterWrapup()
        Return true if exitAfterWrapup() was called.
        Returns:
        true if exitAfterWrapup was called.
      • iterate

        public boolean iterate()
                        throws KernelException
        Invoke one iteration of the model. An iteration consists of first performing changes queued with requestChange() and type resolution, if necessary, and then invoking prefire(), fire(), and postfire(), in that order. If prefire() returns false, then fire() and postfire() are not invoked, and true is returned. Otherwise, fire() will be called once, followed by postfire(). The return value of postfire() is returned. Note that this method ignores finish and pause requests and thus determines a minimum granularity of the execution. Set the state of the manager to ITERATING. This method is read synchronized on the workspace.
        Returns:
        True if postfire() is not called, otherwise, return the value returned by postfire().
        Throws:
        KernelException - If the model throws it, or if there is no container.
      • notifyListenersOfException

        public void notifyListenersOfException​(java.lang.Exception exception)
        Notify all the execution listeners of an exception. If there are no listeners, then print the exception information to the standard error stream. This is intended to be used by threads that are involved in an execution as a mechanism for reporting errors. As an example, in a threaded domain, each thread should catch all exceptions and report them using this method. This method is merely calls notifyListenersOfThrowable(Throwable).
        Parameters:
        exception - The exception.
      • notifyListenersOfThrowable

        public void notifyListenersOfThrowable​(java.lang.Throwable throwable)
        Notify all the execution listeners of a Throwable. If there are no listeners, then print the throwable information to the standard error stream. This is intended to be used by threads that are involved in an execution as a mechanism for reporting errors. As an example, in a threaded domain, each thread should catch all exceptions and report them using this method. This method defers the actual reporting to a new thread because it requires obtaining a lock on this manager, and that could cause deadlock.
        Parameters:
        throwable - The throwable
      • pause

        public void pause()
        Set a flag requesting that execution pause at the next opportunity (between iterations). This method calls stopFire() on the toplevel composite actor to ensure that the manager's execution thread becomes active again. Actors are expected to react to stopFire() by returning as soon as possible from their fire() methods, thus completing an iteration. For example, in the case of PN, an iteration only ends if deadlock occurs, which may never happen. Calling stopFire() truncates the iteration. The thread controlling the execution (the one that calls execute()) will be suspended the next time through the iteration loop. To resume execution, call resume().
        See Also:
        Executable.stopFire()
      • pauseOnBreakpoint

        public void pauseOnBreakpoint​(java.lang.String breakpointMessage)
        The thread that calls this method will wait until resume() has been called.

        Note: This method will block. It should only be called from the executing thread (the thread that is executing the model). Do not call this method from the same thread that will call resume().

        Parameters:
        breakpointMessage - The message to print when paused on a breakpoint.
      • preinitializeAndResolveTypes

        public void preinitializeAndResolveTypes()
                                          throws KernelException
        Preinitialize the model. This calls the preinitialize() method of the container, followed by the resolveTypes() methods. Set the Manager's state to PREINITIALIZING. Note that this method may be invoked without actually running the method, but the calling code must make sure that the Manager's state is reset to IDLE. This method is read synchronized on the workspace.
        Throws:
        KernelException - If the model throws it.
        IllegalActionException - If the model is already running, or if there is no container.
      • preinitializeIfNecessary

        public void preinitializeIfNecessary()
                                      throws KernelException
        If the workspace version has changed since the last invocation of preinitializeAndResolveTypes(), then invoke it now and set the state of the Manager to IDLE upon completion. This can be used during editing a model to check types, to expand higher-order components, or to establish connections between Publisher and Subscriber actors.
        Throws:
        KernelException - If thrown while preinitializing and resolving types.
      • preinitializeThenWrapup

        public static void preinitializeThenWrapup​(Actor actor)
                                            throws KernelException
        Invoke preinitialize() and wrapup().

        If the model has not been preinitialized since the last change to its structure, that must be done now for the result to be accurate. This is because higher-order components and Publisher and Subscriber connections may not have yet been created.

        Parameters:
        actor - The actor upon which to call preinitialize() on its toplevel.
        Throws:
        KernelException - If thrown when a Manager is added to the top level or if preinitialize() fails.
      • removeExecutionListener

        public void removeExecutionListener​(ExecutionListener listener)
        Remove a listener from the list of listeners that are notified of execution events. If the specified listener is not on the list, do nothing.
        Parameters:
        listener - The listener to remove.
        See Also:
        addExecutionListener(ExecutionListener)
      • requestInitialization

        public void requestInitialization​(Actor actor)
        Queue an initialization request. The specified actor will be initialized at an appropriate time, in the iterate() method, by calling its preinitialize() and initialize() methods. This method should be called when an actor is added to a model through a mutation in order to properly initialize the actor.
        Parameters:
        actor - The actor to initialize.
      • resolveTypes

        public void resolveTypes()
                          throws TypeConflictException
        Check types on all the connections and resolve undeclared types. If the container is not an instance of TypedCompositeActor, do nothing. Set the Manager's state to RESOLVING_TYPES. This method is write-synchronized on the workspace.
        Throws:
        TypeConflictException - If a type conflict is detected.
      • resume

        public void resume()
        If the model is paused, resume execution. This method must be called from a different thread than that controlling the execution, since the thread controlling the execution is suspended.
      • run

        public void run()
        Execute the model, catching all exceptions. Use this method to execute the model within the calling thread, but to not throw exceptions. Instead, the exception is handled using the notifyListenersOfException() method. Except for its exception handling, this method has exactly the same behavior as execute().
        Specified by:
        run in interface java.lang.Runnable
      • setExecutionIdentifier

        public void setExecutionIdentifier​(java.lang.Object executionIdentifier)
        Set the execution identifier object. Any throwables that occur in current execution cycle are associated with this identifier. The execution identifier is reset in preinitialize().
        Parameters:
        executionIdentifier - The execution identifier object
        See Also:
        getExecutionIdentifier(Throwable)
      • setStatusMessage

        public void setStatusMessage​(java.lang.String message)
        Set the status message, such as the amount of time consumed. This method is called to update the status bar, so the output should be short.
        Parameters:
        message - The message to be displayed.
        See Also:
        getStatusMessage()
      • setWaitingThread

        public void setWaitingThread​(java.lang.Thread thread)
        Indicate that the specified thread is waiting and can be interrupted in the event that a change request is made.
        Parameters:
        thread - The thread that is waiting, or null to indicate that no thread is waiting.
        See Also:
        getWaitingThread()
      • shortDescription

        @Deprecated
        public static java.lang.String shortDescription​(java.lang.Throwable throwable)
        Deprecated.
        Instead ptolemy.util.MessageHandler.shortDescription()
        Return a short description of the throwable.
        Parameters:
        throwable - The throwable
        Returns:
        If the throwable is an Exception, return "Exception", if it is an Error, return "Error", if it is a Throwable, return "Throwable".
      • startRun

        public void startRun()
                      throws IllegalActionException
        Start an execution in another thread and return. Any exceptions that occur during the execution of the model are handled by the notifyListenersOfException() method.
        Throws:
        IllegalActionException - If the model is already running, e.g. the state is not IDLE.
      • stop

        public void stop()
        If the state is not IDLE, set a flag to request that execution stop and exit in a completely deterministic fashion at the end of the next toplevel iteration. This method may be called from within an actor to stop the execution of the model. This will result in stop() being called on the top level CompositeActor, although not necessarily immediately. This is basically an alias for finish().

        Note that in general, it is best to get that director and call finish() and stopFire() on the director than it is to call Manager.stop().

        The reason that it is better to call Director.finish() is that if Manager.stop() is called inside a RunCompositeActor then only the inside execution will be stopped, not the outside one. It is also not correct to call stop() on the directory because Director.stop() requests immediate stopping. To give determinate stopping, call Director.finish() so that the current iteration is completed.

        In multithreaded domains, Director.stopFire is called to request that all actors conclude ongoing firings.

      • terminate

        @Deprecated
        public void terminate()
        Deprecated.
        Terminate the currently executing model with extreme prejudice. This leaves the state of the manager in CORRUPTED, which means that the model cannot be executed again. A new model must be created, with a new manager, to execute again. This method is not intended to be used as a normal route of stopping execution. To normally stop execution, call the finish() method instead. This method should be called only when execution fails to terminate by normal means due to certain kinds of programming errors (infinite loops, threading errors, etc.).

        If the model execution was started in a separate thread (using startRun()), then that thread is killed unceremoniously (using a method that is now deprecated in Java, for obvious reasons). This method also calls terminate on the toplevel composite actor.

        This method is not synchronized because we want it to execute as soon as possible.

      • timeAndMemory

        public static java.lang.String timeAndMemory​(long startTime)
        Return a string with the elapsed time since startTime, and the amount of memory used.
        Parameters:
        startTime - The start time in milliseconds. For example, the value returned by (new Date()).getTime().
        Returns:
        A string with the elapsed time since startTime, and the amount of memory used.
      • timeAndMemory

        public static java.lang.String timeAndMemory​(long startTime,
                                                     long totalMemory,
                                                     long freeMemory)
        Return a string with the elapsed time since startTime, and the amount of memory used. the value returned by (new Date()).getTime().
        Parameters:
        startTime - The start time in milliseconds. For example, the value returned by (new Date()).getTime().
        totalMemory - The total amount of memory used in kilobytes.
        freeMemory - The total amount of memory free in kilobytes.
        Returns:
        A string with the elapsed time since startTime, and the amount of memory used.
      • waitForCompletion

        public void waitForCompletion()
        If there is an active thread created by startRun(), then wait for it to complete and return. The wait is accomplished by calling the join() method on the thread. If there is no active thread, then wait until the manager state is idle by calling wait().
        See Also:
        startRun()
      • _makeManagerOf

        protected void _makeManagerOf​(CompositeActor compositeActor)
        Make this manager the manager of the specified composite actor. If the composite actor is not null, then the manager is removed from the directory of the workspace. If the composite actor is null, then the manager is not returned to the directory of the workspace, which may result in it being garbage collected. This method should not be called directly. Instead, call setManager in the CompositeActor class (or a derived class).
        Parameters:
        compositeActor - The composite actor that this manager will manage.
      • _notifyListenersOfCompletion

        @Deprecated
        protected void _notifyListenersOfCompletion()
        Deprecated.
        Notify listeners that execution has completed.
      • _notifyListenersOfSuccessfulCompletion

        protected void _notifyListenersOfSuccessfulCompletion()
        Notify listeners that execution has completed successfully.
      • _notifyListenersOfStateChange

        protected void _notifyListenersOfStateChange()
        Propagate the state change event to all the execution listeners.
      • _registerShutdownHook

        protected void _registerShutdownHook()
        Register a shutdown hook to gracefully stop the execution of a model if the JVM is shut down (by control-C, the user logging out, etc.).
      • _setState

        protected void _setState​(Manager.State newState)
        Set the state of execution and notify listeners if the state actually changes.
        Parameters:
        newState - The new state.