2003/12/16 22:35:20
[org.ibex.core.git] / src / org / xwt / Scheduler.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.util.*;
5 import org.xwt.js.*;
6 import org.xwt.util.*;
7
8 /** Implements cooperative multitasking */
9 public class Scheduler {
10
11     // Public API Exposed to org.xwt /////////////////////////////////////////////////
12
13     private static Scheduler singleton;
14     public static interface Task { public abstract void perform() throws Exception; }
15
16     /** adds a task to the back of the queue */
17     public static void add(Task t) { singleton.runnable.append(t); }
18
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); }
21
22     public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
23
24     // API which must be supported by subclasses /////////////////////////////////////
25
26     /**
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.
31      */
32     public void run() { defaultRun(); }
33     protected Scheduler() { }
34
35
36     // Default Implementation //////////////////////////////////////////////////////
37
38     protected static Queue runnable = new Queue(50);
39     public void defaultRun() {
40         while(true) {
41             Task t = (Task)runnable.remove(true);
42             try {
43                 t.perform();
44                 // FEATURE: be smarter about this
45                 if (t != Surface.renderAll) add(Surface.renderAll);
46             } catch (JSExn e) {
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);
52             }
53             // if an Error is thrown it will cause the engine to quit
54         }
55     }
56 }