1 24 25 package com.mckoi.database; 26 27 import java.util.*; 28 import com.mckoi.debug.*; 29 30 43 44 class DatabaseDispatcher extends Thread { 45 46 private ArrayList event_queue = new ArrayList(); 47 48 private TransactionSystem system; 49 50 private boolean finished; 51 52 55 DatabaseDispatcher(TransactionSystem system) { 56 this.system = system; 57 setDaemon(true); 58 setName("Mckoi - Database Dispatcher"); 59 finished = false; 60 start(); 61 } 62 63 72 Object createEvent(Runnable runnable) { 73 return new DatabaseEvent(runnable); 74 } 75 76 80 synchronized void postEvent(int time_to_wait, Object event) { 81 DatabaseEvent evt = (DatabaseEvent) event; 82 event_queue.remove(event); 84 evt.time_to_run_event = System.currentTimeMillis() + time_to_wait; 86 int index = Collections.binarySearch(event_queue, event); 88 if (index < 0) { 89 index = -(index + 1); 90 } 91 event_queue.add(index, event); 92 93 notifyAll(); 94 } 95 96 99 synchronized void finish() { 100 finished = true; 101 notifyAll(); 102 } 103 104 105 public void run() { 106 while (true) { 107 try { 108 109 DatabaseEvent evt = null; 110 synchronized (this) { 111 while (evt == null) { 112 if (finished) { 114 return; 115 } 116 117 if (event_queue.size() > 0) { 118 evt = (DatabaseEvent) event_queue.get(0); 120 long diff = evt.time_to_run_event - System.currentTimeMillis(); 121 if (diff >= 0) { 123 evt = null; 124 wait((int) diff); 125 } 126 } 127 else { 128 wait(); 130 } 131 } 132 event_queue.remove(0); 134 } 135 136 evt.runnable.run(); 138 139 } 140 catch (Throwable e) { 141 system.Debug().write(Lvl.ERROR, this, "SystemDispatchThread error"); 142 system.Debug().writeException(e); 143 } 144 } 145 } 146 147 149 class DatabaseEvent implements Comparable { 150 private long time_to_run_event; 151 private Runnable runnable; 152 153 DatabaseEvent(Runnable runnable) { 154 this.runnable = runnable; 155 } 156 157 public int compareTo(Object ob) { 158 DatabaseEvent evt2 = (DatabaseEvent) ob; 159 long dif = time_to_run_event - evt2.time_to_run_event; 160 if (dif > 0) { 161 return 1; 162 } 163 else if (dif < 0) { 164 return -1; 165 } 166 return 0; 167 } 168 } 169 170 171 } 172 | Popular Tags |