1 package net.javacoding.jspider.core.threading; 2 3 4 import net.javacoding.jspider.core.logging.LogFactory; 5 import net.javacoding.jspider.core.logging.Log; 6 import net.javacoding.jspider.core.task.WorkerTask; 7 8 9 17 class WorkerThread extends Thread { 18 19 public static final int WORKERTHREAD_IDLE = 0; 20 public static final int WORKERTHREAD_BLOCKED = 1; 21 public static final int WORKERTHREAD_BUSY = 2; 22 23 24 25 protected int state; 26 27 28 protected boolean assigned; 29 30 31 protected boolean running; 32 33 34 protected WorkerThreadPool stp; 35 36 37 protected WorkerTask task; 38 39 45 public WorkerThread(WorkerThreadPool stp, String name, int i) { 46 super(stp, name + " " + i); 47 this.stp = stp; 48 running = false; 49 assigned = false; 50 state = WORKERTHREAD_IDLE; 51 } 52 53 57 public boolean isAvailable() { 58 return (!assigned) && running; 59 } 60 61 65 public boolean isOccupied() { 66 return assigned; 67 } 68 69 73 public synchronized void assign(WorkerTask task) { 74 if ( !running ) { 75 throw new RuntimeException ("THREAD NOT RUNNING, CANNOT ASSIGN TASK !!!"); 77 } 78 if (assigned) { 79 throw new RuntimeException ("THREAD ALREADY ASSIGNED !!!"); 81 } 82 this.task = task; 83 assigned = true; 84 notify(); 85 } 86 87 90 public synchronized void stopRunning() { 91 if ( ! running ) { 92 throw new RuntimeException ("THREAD NOT RUNNING - CANNOT STOP !"); 93 } 94 if ( assigned ) { 95 try { 96 this.wait(); 97 } catch (InterruptedException e) { 98 Thread.currentThread().interrupt(); 99 } 100 } 101 running = false; 102 notify(); 103 } 104 105 109 public int getState ( ) { 110 return state; 111 } 112 113 116 public synchronized void run() { 117 running = true; 118 119 Log log = LogFactory.getLog(WorkerThread.class); 120 log.debug("Worker thread (" + this.getName() + ") born"); 121 122 synchronized (stp) { 123 stp.notify(); 124 } 125 126 while (running) { 127 if (assigned) { 128 state = WORKERTHREAD_BLOCKED; 129 task.prepare(); 130 state = WORKERTHREAD_BUSY; 131 try { 132 task.execute(); 133 task.tearDown(); 134 } catch (Exception e) { 135 log.fatal("PANIC! Task " + task + " threw an excpetion!", e); 136 System.exit(1); 137 } 138 139 synchronized (stp) { 140 assigned = false; 141 task = null; 142 state = WORKERTHREAD_IDLE; 143 stp.notify(); 144 this.notify(); } 146 147 } 148 try { 149 wait(); 150 } catch (InterruptedException e) { 151 Thread.currentThread().interrupt(); 152 } 153 } 154 155 156 log.debug("Worker thread (" + this.getName() + ") dying"); 157 } 158 } 159 | Popular Tags |