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