package jutil; /** * The Sim framework consists of the Simulator, Events, and * priority queue. */ public class Simulator implements java.io.Serializable { /** * Scheduled events are placed in this queue in order * of their firing times. Currently, the priority * queue is implemented as a binary heap with capacity * 512. Consider replacing this implementation with * a sorted list or a larger binary heap. */ protected PriorityQueue events = new BinaryHeap(); /** * The simulated time. */ protected int clock = 0; /** * Set to true to see the clock and event queue after * each event is fired. */ protected boolean debug = true; /** * Adds events to the events queue. */ public void schedule(Event e) throws OverflowException { events.insert(e); } public Simulator(PriorityQueue q) { events = q; clock = 0; debug = true; } /** * Initializes event queue as a binary heap. */ public Simulator() { this(new BinaryHeap()); } /** * Repeatedly removes the next event from the event queue, updates * the clock, and fires the event. If firing the event creates a new * event, then this event is scheduled. */ public void run() { try { while(!events.isEmpty()) { if (debug) { System.out.println("clock = " + clock); System.out.println("schedule = " + events); } Event next = (Event)events.deleteMin(); clock = next.getFireTime(); Event e = next.fire(); if (e != null) schedule(e); } System.out.println("done"); } catch(Exception e) { handle(e); } } /** * Handles errors by terminating the simulation. Errors * are either queue overflow or empty queue errors. * * @param e The exception thrown. */ protected void handle(Exception e) { System.err.println(e.getMessage()); System.exit(1); } }