1 package com.protomatter.util; 2 3 52 53 import java.util.*; 54 import com.protomatter.syslog.Syslog; 55 import com.protomatter.pool.*; 56 57 61 public final class WorkQueue 62 extends GrowingObjectPool 63 { 64 private static int queueNumber = 0; 66 67 private int numThreads = 0; 68 private int id = 0; 69 private ThreadGroup threadGroup = null; 70 71 private static synchronized int nextQueueNumber() 72 { 73 return ++queueNumber; 74 } 75 76 80 public WorkQueue(int numThreads) 81 { 82 this(null, numThreads); 83 } 84 85 89 public WorkQueue(String name, int numThreads) 90 { 91 super(false); 92 try 93 { 94 init(new Hashtable()); 95 } 96 catch (Exception x) 97 { 98 Syslog.log(this, x); 100 } 101 102 this.id = nextQueueNumber(); 103 if (name == null) 104 this.threadGroup = new ThreadGroup ("WorkQueueGroup[id="+id+"]"); 105 else 106 this.threadGroup = new ThreadGroup ("WorkQueueGroup[id="+id+", name="+name+"]"); 107 this.threadGroup.setDaemon(true); 108 109 this.numThreads = numThreads; 110 for (int i=0; i<numThreads; i++) 111 { 112 WorkQueueThread t = new WorkQueueThread(this, threadGroup, id, name, i); 113 t.start(); 114 } 115 } 116 117 public ObjectPoolObject createObjectPoolObject() 118 { 119 return null; 120 } 121 122 126 public int getNumThreads() 127 { 128 return this.numThreads; 129 } 130 131 134 public int getNumWorkers() 135 { 136 return (this.numThreads - getNumWaiters()); 137 } 138 139 143 public int getQueueLength() 144 { 145 return getObjectPoolSize(); 146 } 147 148 152 final Runnable getWork() 153 throws Exception  154 { 155 Object o = checkout(); 156 if (o instanceof Runnable ) 157 return (Runnable )o; 158 if (o != null) 159 return ((WorkQueueOPO)o).getRunnable(); 160 return null; 161 } 162 163 166 public final void addWork(Runnable r) 167 { 168 try 169 { 170 if (r instanceof ObjectPoolObject) 171 checkin((ObjectPoolObject)r); 172 else 173 checkin(new WorkQueueOPO(r)); 174 } 175 catch (Exception x) 176 { 177 Syslog.log(this, x); 179 } 180 } 181 182 private class WorkQueueOPO 183 implements ObjectPoolObject 184 { 185 private Runnable runnable = null; 186 private boolean valid = true; 187 188 public WorkQueueOPO(Runnable r) 189 { 190 this.runnable = r; 191 this.valid = true; 192 } 193 194 public Runnable getRunnable() 195 { 196 return this.runnable; 197 } 198 199 public void deleteObjectPoolObject() 200 { 201 this.valid = false; 202 } 203 204 public boolean isObjectPoolObjectValid() 205 { 206 return this.valid; 207 } 208 209 public void beforeObjectPoolObjectCheckout() 210 { 211 } 212 213 public void afterObjectPoolObjectCheckin() 214 { 215 } 216 } 217 } 218
| Popular Tags
|