1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
8 /** Implements cooperative multitasking */
9 public class Scheduler {
11 // FIXME: prepending events messes with keysate -- make a "no re-ordering" invariant?
13 // Public API Exposed to org.xwt /////////////////////////////////////////////////
15 private static Scheduler singleton;
16 public static interface Task { public abstract void perform() throws Exception; }
18 /** adds a task to the back of the queue */
19 public static void add(Task t) { singleton.runnable.append(t); }
21 /** adds a task to the front of the queue (guaranteed to run next) */
22 public static void addAtFront(Task t) { singleton.runnable.prepend(t); }
24 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
26 // API which must be supported by subclasses /////////////////////////////////////
29 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
30 * Surface.renderAll() after performing a Task if no tasks remain
31 * in the queue. A scheduler may choose to invoke
32 * Surface.renderAll() more often than that if it so chooses.
34 public void run() { defaultRun(); }
35 protected Scheduler() { }
38 // Default Implementation //////////////////////////////////////////////////////
40 protected static Queue runnable = new Queue(50);
41 public void defaultRun() {
43 Task t = (Task)runnable.remove(true);
46 // FEATURE: be smarter about this
47 //if (t != Surface.renderAll) add(Surface.renderAll);
48 Surface.renderAll.perform();
50 Log.log(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
51 Log.log(Scheduler.class, e.toString());
52 } catch (Exception e) {
53 Log.log(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
54 Log.log(Scheduler.class, e);
56 // if an Error is thrown it will cause the engine to quit