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