8a5cd3226d9f5d286abf80d23580d78e1276be69
[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     public static void add(Task t) { singleton.runnable.append(t); }
16     public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
17
18     // API which must be supported by subclasses /////////////////////////////////////
19
20     /**
21      *  SCHEDULER INVARIANT: all scheduler implementations MUST invoke
22      *  Surface.renderAll() after performing a Task if no tasks remain
23      *  in the queue.  A scheduler may choose to invoke
24      *  Surface.renderAll() more often than that if it so chooses.
25      */
26     public void run() { defaultRun(); }
27     protected Scheduler() { }
28
29
30     // Default Implementation //////////////////////////////////////////////////////
31
32     protected static Queue runnable = new Queue(50);
33     public void defaultRun() {
34         while(true) {
35             Task t = (Task)runnable.remove(true);
36             try {
37                 t.perform();
38                 // FEATURE: be smarter about this
39                 if (t != Surface.renderAll) add(Surface.renderAll);
40             } catch (JSExn e) {
41                 Log.log(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
42                 Log.log(Scheduler.class, e.toString());
43             } catch (Exception e) {
44                 Log.log(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
45                 Log.log(Scheduler.class, e);
46             }
47             // if an Error is thrown it will cause the engine to quit
48         }
49     }
50 }