2003/11/05 10:25:00
[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     public static abstract class Task { public abstract void perform(); }
14     public static void add(Task t) { singleton.runnable.append(t); }
15     public static void init() { singleton.run(); }
16
17
18     // API which must be supported by subclasses /////////////////////////////////////
19
20     protected Scheduler() { }
21
22     /**
23      *  INVARIANT: all scheduler implementations MUST invoke
24      *  Surface.renderAll() after performing a Task if no tasks remain
25      *  in the queue.  A scheduler may choose to invoke
26      *  Surface.renderAll() more often than that if it so chooses.
27      */
28     public void run() { defaultRun(); }
29
30
31     // Default Implementation /////////////////////////////////////
32
33     protected static Queue runnable = new Queue(50);
34     private static final Scheduler singleton = Platform.getScheduler();
35     public void defaultRun() {
36         while(true) {
37             Task t = (Task)runnable.remove(true);
38             try {
39                 t.perform();
40                 // FIXME: be smarter about this
41                 Surface.renderAll();
42             } catch (Exception e) {
43                 Log.log(Scheduler.class, "Task threw an exception: " + e);
44                 Log.log(Scheduler.class, e);
45             }
46         }
47     }
48 }