1 24 25 package com.mckoi.database; 26 27 import com.mckoi.debug.*; 28 29 35 36 final class WorkerThread extends Thread { 37 38 42 private static final boolean DISPLAY_COMMAND_TIME = false; 43 44 47 private boolean shutdown; 48 49 52 private Runnable command; 53 54 57 private long start_time; 58 59 62 private WorkerPool worker_pool; 63 64 67 public WorkerThread(WorkerPool worker_pool) { 68 super(); 69 setName("Mckoi - Worker"); 71 this.worker_pool = worker_pool; 72 command = null; 73 shutdown = false; 74 } 75 76 79 public final DebugLogger Debug() { 80 return worker_pool.Debug(); 81 } 82 83 85 88 synchronized void shutdown() { 89 shutdown = true; 90 notifyAll(); 91 } 92 93 96 void execute(User user, DatabaseConnection database_connection, 97 Runnable runner) { 98 synchronized (this) { 100 if (command == null) { 101 this.command = runner; 102 notifyAll(); 103 } 104 else { 105 throw new RuntimeException ( 106 "Deadlock Error, tried to execute command on running worker."); 107 } 108 } 109 } 110 111 114 public synchronized void run() { 115 while (true) { 116 try { 117 if (command != null) { 119 try { 120 start_time = System.currentTimeMillis(); 122 command.run(); 124 } 125 finally { 126 command = null; 127 long elapsed_time = System.currentTimeMillis() - start_time; 129 if (DISPLAY_COMMAND_TIME) { 130 System.err.print("[Worker] Completed command in "); 131 System.err.print(elapsed_time); 132 System.err.print(" ms. "); 133 System.err.println(this); 134 } 135 } 136 } 137 138 worker_pool.notifyWorkerReady(this); 141 while (command == null) { 144 try { 145 wait(); 147 } 148 catch (InterruptedException e) { } 149 if (shutdown) { 151 return; 152 } 153 } 154 155 } 156 catch (Throwable e) { 157 Debug().write(Lvl.ERROR, this, 158 "Worker thread interrupted because of exception:\n" + 159 e.getMessage()); 160 Debug().writeException(e); 161 } 162 } 163 } 164 165 } 166 | Popular Tags |