cz.zcu.fav.kiv.jsim
Class JSimSimulation

java.lang.Object
  extended by cz.zcu.fav.kiv.jsim.JSimSimulation

public class JSimSimulation
extends java.lang.Object

The JSimSimulation class instances represent theoretical simulation models, containing processes, queues, and other elements. Every process and queue must have a simulation specified as a constructor parameter, otherwise the creation will not be successful. To the user, the JSimSimulation class provides the step() method – execution of one simulation step. Alternatively, the runGUI() method can be used, causing the simulation to run in graphic mode.

Since:
J-Sim version 0.1.0
Version:
J-Sim version 0.6.0
Author:
Jarda KAČER, Pavel DOMECKÝ

Field Summary
private  JSimCalendar calendar
          The simulation's calendar of events.
protected  boolean firstStepExecuted
          Flag saying that the first step of simulation has been executed.
private  java.lang.Object graphicLock
          Lock used when switching between the simulation and its main GUI window.
protected  JSimChange guiUpdate
          Observable object notifying the GUI about possible changes.
protected  double lastGUIUpdate
          Last GUI update time.
private static java.util.logging.Logger logger
          Common logger for all instances of this class.
protected  JSimMainWindow mainWindow
          The simulation's main window.
protected  boolean mainWindowHasAlreadyExisted
          Flag indicating that the main window has already been opened (and maybe closed).
protected  JSimSimulationMode mode
          The simulation's mode – text, GUI batch, GUI interactive.
private  java.lang.String myName
          The simulation's name.
private  int myNumber
          The simulation's number.
static long NEW_PROCESS_FORBIDDEN
           
static long NEW_QUEUE_FORBIDDEN
           
static long NEW_SEMAPHORE_FORBIDDEN
           
private  long newProcessNumber
          Number for a newly created process.
private  long newQueueNumber
          Number for a newly created queue.
private  long newSemaphoreNumber
          Number for a newly created semaphore.
protected  double nextGUIUpdateDelta
          GUI update delta.
private static int noOfSimulations
          Number of simulations running in this JVM instance.
private  java.util.SortedSet<JSimProcess> notStartedProcesses
          A set containing processes created during last step and not started yet.
private  long numberOfProcesses
          Number of processes currently present within the simulation.
private  long numberOfQueues
          Number of queues currently present within the simulation.
private  long numberOfSemaphores
          Number of semaphores currently present within the simulation.
static int PRN_ERROR
           
static int PRN_MESSAGE
           
private  java.util.SortedSet<JSimProcess> processes
          All processes of the simulation.
private  java.util.SortedSet<JSimProcess> processesForGUI
          All processes that have ever existed in the simulation.
private  java.util.SortedSet<JSimHead> queues
          All queues of the simulation.
protected  JSimProcess runningProcess
          The currently running process.
private  java.util.SortedSet<JSimSemaphore> semaphores
          All semaphores of the simulation.
private  JSimSimulationState simulationState
          The simulation's state – not started, in progress, terminated.
protected  java.lang.Object stepLock
          Lock used to synchronize (possible) concurrent calls to step().
private  double time
          The simulation's current time.
private  java.lang.Object waitForWindowClosureLock
          Lock used when the simulation waits in waitForWindowClosure().
private  boolean waitingForWindowClosure
          Flag saying that the simulation is just now waiting in waitForWindowClosure().
protected  boolean windowOpen
          Flag saying that the main window is open.
 
Constructor Summary
JSimSimulation(java.lang.String name)
          Creates a new simulation with no processes, no queues and no graphic window.
JSimSimulation(java.lang.String name, JSimSimulationMode mode)
          Creates a new simulation with no processes, no queues and no graphic window.
JSimSimulation(java.lang.String name, JSimSimulationMode mode, double guiUpdateDelta)
          Creates a new simulation with no processes, no queues and no graphic window.
 
Method Summary
protected  void addEntryToCalendar(double absoluteTime, JSimProcess process)
          Adds a new event to the calendar, with the specified absolute time and the specified process.
protected  void addProcess(JSimProcess process)
          Adds a new process to the simulation.
protected  void addQueue(JSimHead queue)
          Adds a new queue to the simulation.
 void addSemaphore(JSimSemaphore semaphore)
          Adds a new semaphore to the simulation.
private  void deleteAllProcesses()
          Deletes all processes from the simulation.
protected  int deleteEntriesInCalendar(JSimProcess process, boolean all)
          Deletes one or more entries in the calendar, concerning a process.
protected  void deleteProcess(JSimProcess process)
          Deletes a process from the simulation.
 void error(java.lang.String s)
          Prints out a text error message, either to the error output or to the simulation window.
 double getCurrentTime()
          Returns the simulation's current time.
 long getFreeProcessNumber()
          Returns a unique number that can be assigned to a newly created process.
 long getFreeQueueNumber()
          Returns a unique number that can be assigned to a newly created queue.
 long getFreeSemaphoreNumber()
          Returns a unique number that can be assigned to a newly created semaphore.
 java.lang.Object getGraphicLock()
          Returns the lock object used for synchronization between the simulation and its GUI window.
 JSimChange getChange()
          Returns an observable object notifying the GUI about possible changes.
 long getNumberOfProcesses()
          Returns the number of processes present within the simulation.
 long getNumberOfQueues()
          Returns the number of queues present within the simulation.
 long getNumberOfSemaphores()
          Returns the number of semaphores present within the simulation.
 java.util.SortedSet<? extends JSimDisplayable> getObjectsToBeDisplayed(int elementType)
          Returns a set containing information about simulation elements that are to be displayed in the GUI.
 JSimProcess getRunningProcess()
          Returns the currently running process.
 JSimSimulationMode getSimulationMode()
          Returns the simulation's mode.
 java.lang.String getSimulationName()
          Returns the simulation's name.
 int getSimulationNumber()
          Returns the simulation's unique number.
 JSimSimulationState getSimulationState()
          Returns the simulation's state.
 java.lang.Object getStepLock()
          Returns the lock object that protects the step() method from being invoked in parallel.
 boolean getWaitingForWindowClosure()
          Returns true if the simulation is waiting in waitForWindowClosure().
 java.lang.Object getWindowClosureLock()
          Returns the lock object used for synchronization between the simulation and its GUI window, while waiting in waitForWindowClosure().
 boolean isRunningGUI()
          Returns true if the simulation is running in a GUI window.
 void message(java.lang.String s)
          Prints out a text message, either to the standard output or to the simulation window.
 void messageNoNL(java.lang.String s)
          Prints out a text message, either to the standard output or to the simulation window, but does not terminate the line.
 void printString(java.lang.String s, int code, boolean newLine)
          Prints a standard message or an error message.
protected  boolean runBatchGUI()
          Opens a graphic window for GUI batch mode and keeps it open.
 boolean runGUI()
          Opens a graphic window and lets the user control the simulation's execution using this window.
 void shutdown()
          Shutdowns the simulation by interrupting all living processes.
protected  boolean startNewProcesses()
          Starts all new processes.
 boolean step()
          Executes one simulation step.
protected  void switchToNobody()
          Switches the execution to the main thread.
 void waitForWindowClosure()
          Suspends the calling thread until the `Quit' button of the main window is pressed.
 void windowIsClosing(JSimMainWindow caller)
          The simulation is informed about the main window's closure.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PRN_MESSAGE

public static final int PRN_MESSAGE
See Also:
Constant Field Values

PRN_ERROR

public static final int PRN_ERROR
See Also:
Constant Field Values

NEW_PROCESS_FORBIDDEN

public static final long NEW_PROCESS_FORBIDDEN
See Also:
Constant Field Values

NEW_QUEUE_FORBIDDEN

public static final long NEW_QUEUE_FORBIDDEN
See Also:
Constant Field Values

NEW_SEMAPHORE_FORBIDDEN

public static final long NEW_SEMAPHORE_FORBIDDEN
See Also:
Constant Field Values

logger

private static final java.util.logging.Logger logger
Common logger for all instances of this class. By default, all logging information goes to a file. Only severe events go to the console, in addition to a file.


myNumber

private final int myNumber
The simulation's number. These numbers are unique for a given JVM instance.


myName

private final java.lang.String myName
The simulation's name.


mode

protected final JSimSimulationMode mode
The simulation's mode – text, GUI batch, GUI interactive.


numberOfProcesses

private long numberOfProcesses
Number of processes currently present within the simulation.


numberOfQueues

private long numberOfQueues
Number of queues currently present within the simulation.


numberOfSemaphores

private long numberOfSemaphores
Number of semaphores currently present within the simulation.


runningProcess

protected JSimProcess runningProcess
The currently running process. At most one process can run at the same time.


newProcessNumber

private long newProcessNumber
Number for a newly created process. Alike numberOfProcesses, this number is never decremented so every process has its unique number.


newQueueNumber

private long newQueueNumber
Number for a newly created queue. Alike numberOfQueues, this number is never decremented so every queue (JSimHead) has its unique number.


newSemaphoreNumber

private long newSemaphoreNumber
Number for a newly created semaphore. Alike numberOfSemaphores, this number is never decremented so every semaphore (JSimSemaphore) has its unique number.


calendar

private JSimCalendar calendar
The simulation's calendar of events.


time

private double time
The simulation's current time.


simulationState

private JSimSimulationState simulationState
The simulation's state – not started, in progress, terminated.


processes

private java.util.SortedSet<JSimProcess> processes
All processes of the simulation.


processesForGUI

private java.util.SortedSet<JSimProcess> processesForGUI
All processes that have ever existed in the simulation. The list of processes in the GUI window shows even processes that have terminated already.


queues

private java.util.SortedSet<JSimHead> queues
All queues of the simulation.


semaphores

private java.util.SortedSet<JSimSemaphore> semaphores
All semaphores of the simulation.


notStartedProcesses

private java.util.SortedSet<JSimProcess> notStartedProcesses
A set containing processes created during last step and not started yet. It is completely emptied every time startNewProcesses() is called and new processes are started.


graphicLock

private final java.lang.Object graphicLock
Lock used when switching between the simulation and its main GUI window.


stepLock

protected final java.lang.Object stepLock
Lock used to synchronize (possible) concurrent calls to step(). The implicit lock cannot be used since processes use callbacks to the simulation's synchronized methods, e.g. getRunningProcess() in getReady(), and the lock for synchonizing step() must not be released when switching to a process's thread from the main thread.


waitForWindowClosureLock

private final java.lang.Object waitForWindowClosureLock
Lock used when the simulation waits in waitForWindowClosure(). This is only possible when the simulation runs in GUI batch mode.


mainWindow

protected JSimMainWindow mainWindow
The simulation's main window.


windowOpen

protected boolean windowOpen
Flag saying that the main window is open.


waitingForWindowClosure

private boolean waitingForWindowClosure
Flag saying that the simulation is just now waiting in waitForWindowClosure().


firstStepExecuted

protected boolean firstStepExecuted
Flag saying that the first step of simulation has been executed. This flag is important in GUI batch mode where the simulation itself takes care about the GUI main window.


mainWindowHasAlreadyExisted

protected boolean mainWindowHasAlreadyExisted
Flag indicating that the main window has already been opened (and maybe closed). The flag is relevant in batch GUI mode only where it is necessary to distinguish whether messages should go to the main window or to the console. If an output/step request is received, the main window must be open, but only if it has not been opened/closed yet.


guiUpdate

protected JSimChange guiUpdate
Observable object notifying the GUI about possible changes.


nextGUIUpdateDelta

protected double nextGUIUpdateDelta
GUI update delta. This is a simulation time interval between two consecutive updates of GUI output. Its value does not change during simulation execution. If it is zero, the output is updated after every simulation step. Otherwise, the output is updated only if the difference between the current simulation time and lastGUIUpdate is equal to or greater than this delta.


lastGUIUpdate

protected double lastGUIUpdate
Last GUI update time.


noOfSimulations

private static int noOfSimulations
Number of simulations running in this JVM instance.

Constructor Detail

JSimSimulation

public JSimSimulation(java.lang.String name)
               throws JSimInvalidParametersException
Creates a new simulation with no processes, no queues and no graphic window. The simulation will run in text (console) mode and no graphic output will be allowed.

Parameters:
name - Name of the simulation.
Throws:
JSimInvalidParametersException - This exception is thrown out if the specified name is is null.

JSimSimulation

public JSimSimulation(java.lang.String name,
                      JSimSimulationMode mode)
               throws JSimInvalidParametersException
Creates a new simulation with no processes, no queues and no graphic window. According to the simulation mode specified as a parameter, it will / will not be allowed to use graphic output later. If GUI batch or interactive mode is used, the output will be updated after every step.

Parameters:
name - Name of the simulation.
mode - Simulation mode.
Throws:
JSimInvalidParametersException - This exception is thrown out if the specified name is is null or an invalid simulation mode is given to the constructor.

JSimSimulation

public JSimSimulation(java.lang.String name,
                      JSimSimulationMode mode,
                      double guiUpdateDelta)
               throws JSimInvalidParametersException
Creates a new simulation with no processes, no queues and no graphic window. According to the simulation mode specified as a parameter, it will / will not be allowed to use graphic output later.

Parameters:
name - Name of the simulation.
mode - Simulation mode.
guiUpdateDelta - A simulation time interval after which the GUI output will be updated. If set to zero, the output will be updated after every simulation step. This may be time consuming and inappropriate for some situations.
Throws:
JSimInvalidParametersException - This exception is thrown out if the specified name is is null, an invalid simulation mode is given to the constructor, or if the update interval is less than zero.
Method Detail

addProcess

protected final void addProcess(JSimProcess process)
                         throws JSimInvalidParametersException
Adds a new process to the simulation. You should never call this method. It is called automatically from JSimProcess constructor.

Parameters:
process - The process that has to be added to the simulation.
Throws:
JSimInvalidParametersException - This exception is thrown out if the specified process is null.

addQueue

protected final void addQueue(JSimHead queue)
                       throws JSimInvalidParametersException
Adds a new queue to the simulation. You should never call this method. It is called automatically from JSimHead constructor.

Parameters:
queue - The queue that has to be added to the simulation.
Throws:
JSimInvalidParametersException - This exception is thrown out if the specified queue is null.

addSemaphore

public final void addSemaphore(JSimSemaphore semaphore)
                        throws JSimInvalidParametersException
Adds a new semaphore to the simulation. You should never call this method. It is called automatically from JSimSemaphore constructor.

Parameters:
semaphore - The semaphore that has to be added to the simulation.
Throws:
JSimInvalidParametersException - This exception is thrown out if the specified semaphore is null.

startNewProcesses

protected final boolean startNewProcesses()
Starts all new processes. You should never call this method. New processes are those processes that were added to the simulation between the last and this step from outside the simulation or during the last step from a process. We do not check that the processes are in the process set because a process cannot be removed from the simulation by another process.

Returns:
True if one or more processes were started, false otherwise. False does not mean a failure, just the fact that there were no not-started-yet processes.

deleteProcess

protected final void deleteProcess(JSimProcess process)
Deletes a process from the simulation. You should never call this method. This method is called by a process which is volunteering to die. Other processes, killed during shutdown, do not call this method. We do not care about notStartedProcesses because the process is volunteering to die and therefore has been started already. There is no need to kill the deleted process by interrupt(). It is at the end of its life in finish() and will die as soon as it gets out from this method.

Parameters:
process - The process to be deleted from the simulation.

deleteAllProcesses

private final void deleteAllProcesses()
Deletes all processes from the simulation. Every process is interrupted which causes it to wake-up and finish its run() method. You should never call this method. It is called automatically from shutdown() when sleeping processes (in hold() or passivate()) have to interrupted and terminated.


step

public boolean step()
             throws JSimMethodNotSupportedException
Executes one simulation step. A step is a unit of activity that is terminated by a process' call to the passivate() or hold() method or by a process' death. If there is no process within the simulation or no processes are scheduled or the quit button in GUI batch mode is pressed, simulation will terminate and false will be returned. In all other cases, true will be returned. The method is synchronized with a special lock (stepLock) instead of the implicit one. The reason for not using the implicit lock is that the simulation would block before entering the synchronized(processLock) section because a process would have this lock (processLock) acquired while demanding to call a method synchronized with the implicit lock (e.g. getRunningProcess() in getReady()) and the implicit lock would never be released in step(), even not after passivation of the main thread.

Returns:
False if the step could not be executed because there were no events in the calendar or there were no processes in the simulation or the quit button in the GUI was pressed, true otherwise (the step was successufully completed).
Throws:
JSimKernelPanicException - This exception is thrown out when the state of the simulation cannot be determined or when an inconsistency of J-Sim internal structures (such as the calendar) is revealed.
JSimMethodNotSupportedException - This exception is thrown out when the simulation is running in GUI interactive mode and step() is called from elsewhere than GUI.

shutdown

public void shutdown()
Shutdowns the simulation by interrupting all living processes. You must always call this function, preferably in the finally block at the end of your main program.


getSimulationNumber

public int getSimulationNumber()
Returns the simulation's unique number.

Returns:
The Simulation's unique number.

getSimulationName

public java.lang.String getSimulationName()
Returns the simulation's name.

Returns:
The simulation's name.

getNumberOfProcesses

public final long getNumberOfProcesses()
Returns the number of processes present within the simulation.

Returns:
Number of processes present within the simulation.

getNumberOfQueues

public final long getNumberOfQueues()
Returns the number of queues present within the simulation.

Returns:
Number of queues present within the simulation.

getNumberOfSemaphores

public final long getNumberOfSemaphores()
Returns the number of semaphores present within the simulation.

Returns:
Number of semaphores present within the simulation.

getRunningProcess

public final JSimProcess getRunningProcess()
Returns the currently running process. If no process is running JSimCalendar.NOBODY (=null) will be returned.

Returns:
The currently running process or JSimCalendar.NOBODY.

getFreeProcessNumber

public final long getFreeProcessNumber()
Returns a unique number that can be assigned to a newly created process. You should never call this method.

Returns:
A unique number that can be assigned to a newly created process.

getFreeQueueNumber

public final long getFreeQueueNumber()
Returns a unique number that can be assigned to a newly created queue. You should never call this method.

Returns:
A unique number that can be assigned to a newly created queue.

getFreeSemaphoreNumber

public final long getFreeSemaphoreNumber()
Returns a unique number that can be assigned to a newly created semaphore. You should never call this method.

Returns:
A unique number that can be assigned to a newly created semaphore.

switchToNobody

protected final void switchToNobody()
Switches the execution to the main thread. You should never call this method. This method is called by a process from its hold(), passivate(), or reactivate(). Calling this method does not guarantee the physical thread switch itself, it just sets up the running thread variable.


getCurrentTime

public final double getCurrentTime()
Returns the simulation's current time.

Returns:
The simulation's current time.

getSimulationState

public final JSimSimulationState getSimulationState()
Returns the simulation's state.

Returns:
The simulation's state.

getSimulationMode

public final JSimSimulationMode getSimulationMode()
Returns the simulation's mode.

Returns:
The simulation's mode.

getGraphicLock

public final java.lang.Object getGraphicLock()
Returns the lock object used for synchronization between the simulation and its GUI window. You should never call this method.

Returns:
The lock object used for sychronization between the simulation and its GUI window.

getStepLock

public final java.lang.Object getStepLock()
Returns the lock object that protects the step() method from being invoked in parallel. It is also used for synchronization between the simulation and its GUI window, while being paused. You should never call this method.

Returns:
The lock object that protects the step() method.

getWindowClosureLock

public final java.lang.Object getWindowClosureLock()
Returns the lock object used for synchronization between the simulation and its GUI window, while waiting in waitForWindowClosure(). You should never call this method.

Returns:
The lock object used for synchronization between the simulation and its GUI window.

getChange

public final JSimChange getChange()
Returns an observable object notifying the GUI about possible changes. You should never call this method.

Returns:
An observable object notifying the GUI about possible changes.

getObjectsToBeDisplayed

public java.util.SortedSet<? extends JSimDisplayable> getObjectsToBeDisplayed(int elementType)
                                                                       throws JSimInvalidParametersException
Returns a set containing information about simulation elements that are to be displayed in the GUI. You should never call this method.

Parameters:
elementType - Specifies the type of elements whose information should be returned. Available constants are JSimMainWindow.LIST_TYPE_*.
Returns:
A set containing information about simulation elements.
Throws:
JSimInvalidParametersException - This exception is thrown out if the elementType parameter does not specify a valid type of simulation elements.

addEntryToCalendar

protected void addEntryToCalendar(double absoluteTime,
                                  JSimProcess process)
                           throws JSimInvalidParametersException
Adds a new event to the calendar, with the specified absolute time and the specified process. You should never call this method. Processes themeselves use this method when they have to be scheduled.

Parameters:
absoluteTime - Absolute simulation time of the event being added to the calendar.
process - Process that will be activated at the specified time.
Throws:
JSimInvalidParametersException - This exception is thrown out if the time or the process specified are invalid and were rejected by the calendar.

deleteEntriesInCalendar

protected int deleteEntriesInCalendar(JSimProcess process,
                                      boolean all)
                               throws JSimInvalidParametersException
Deletes one or more entries in the calendar, concerning a process. You should never call this method.

Parameters:
process - Process whose events are to be deleted.
all - Flag saying whether just one (false) or all (true) events of the process should be deleted.
Returns:
Number of events deleted.
Throws:
JSimInvalidParametersException - This exception is thrown out when the process specified is invalid and was rejected by the calendar.

printString

public void printString(java.lang.String s,
                        int code,
                        boolean newLine)
Prints a standard message or an error message. If not running in a GUI window, standard messages are printed to the standard output and error messages to the error output. When running in a GUI window, all messages are printed to the user text area at the bottom of the window. You should never use this method since there are methods message() and error() in the JSimProcess class.

Parameters:
s - The text message to be printed out.
code - Code saying whether it is an info message (PRN_MESSAGE) or an error (PRN_ERROR).
newLine - Flag indicating that the new line character should be appended to the text.

isRunningGUI

public final boolean isRunningGUI()
Returns true if the simulation is running in a GUI window.

Returns:
True if the simulation is running in a GUI window, false otherwise.

runGUI

public final boolean runGUI()
                     throws JSimMethodNotSupportedException
Opens a graphic window and lets the user control the simulation's execution using this window. Does not exit until the user presses the `Quit' button. This method can be used in GUI interactive mode only.

Returns:
True if GUI creation was succesful, false otherwise.
Throws:
JSimMethodNotSupportedException - This exception is thrown out if the simulation is not running in GUI interactive mode.

runBatchGUI

protected final boolean runBatchGUI()
Opens a graphic window for GUI batch mode and keeps it open. The window will exist while the step() will be called from the main program. You should never call this method. It is run automatically from step(), message(), or error() when J-Sim detects that the window should be opened up.

Returns:
True if the creation was succesful, false otherwise.

windowIsClosing

public final void windowIsClosing(JSimMainWindow caller)
The simulation is informed about the main window's closure. You should never use this method. Only the main window can call this method although it is public. Used in GUI interactive mode.

Parameters:
caller - The main window informing about its closure.

waitForWindowClosure

public void waitForWindowClosure()
                          throws JSimMethodNotSupportedException
Suspends the calling thread until the `Quit' button of the main window is pressed. Use this method in GUI batch mode to keep the main window open after the simulation is done (when step() is no longer called) to let the user see the results. The simulation need not necessarily be in terminated state.

Throws:
JSimMethodNotSupportedException - This exception is thrown out if the simulation is not running in GUI batch mode.

getWaitingForWindowClosure

public boolean getWaitingForWindowClosure()
Returns true if the simulation is waiting in waitForWindowClosure().

Returns:
True if the simulation is waiting in waitForWindowClosure(), false otherwise.

message

public void message(java.lang.String s)
Prints out a text message, either to the standard output or to the simulation window.

Parameters:
s - The message to be printed out.

messageNoNL

public void messageNoNL(java.lang.String s)
Prints out a text message, either to the standard output or to the simulation window, but does not terminate the line.

Parameters:
s - The message to be printed out.

error

public void error(java.lang.String s)
Prints out a text error message, either to the error output or to the simulation window.

Parameters:
s - The error message to be printed out.


Copyright © 2000-2006 University of West Bohemia. Licensed under the Academic Free License v. 2.1. Build date 20060812.