ThreadPool bugfix
authoradam <adam@megacz.com>
Sun, 15 Jul 2007 23:08:51 +0000 (23:08 +0000)
committeradam <adam@megacz.com>
Sun, 15 Jul 2007 23:08:51 +0000 (23:08 +0000)
darcs-hash:20070715230851-5007d-144d7b23a863e9c0866fd32d56a17d32ec934af4.gz

src/org/ibex/util/ThreadPool.java

index 16eeb83..0fb6d07 100644 (file)
@@ -35,7 +35,7 @@ public final class ThreadPool {
         this.numIdleThreads = 0;
         this.idleThreads    = new PooledThread[minThreads];
         for(int i=0; i<this.idleThreads.length; i++)
-            this.idleThreads[i] = new PooledThread();
+            new PooledThread();
     }
 
     public synchronized void start(Runnable r) {
@@ -59,12 +59,7 @@ public final class ThreadPool {
     private class PooledThread extends Thread {
         private Runnable runnable = null;
         public PooledThread() {
-            synchronized(ThreadPool.this) {
-                if (numIdleThreads >= idleThreads.length)
-                    throw new Error("this should not happen");
-                numThreads++;
-                idleThreads[numIdleThreads++] = this;
-            }
+            synchronized(ThreadPool.this) { numThreads++; }
             start();
         }
         public synchronized void start(Runnable runnable) {
@@ -76,21 +71,26 @@ public final class ThreadPool {
         public void run() {
             try {
                 while(true) {
+                    synchronized(this) {
+                        if (runnable==null)
+                            synchronized(ThreadPool.this) {
+                                /* if the idle array is full, just let ourselves die */
+                                if (numIdleThreads > minIdleThreads && numThreads > minThreads) return;
+                                /* otherwise put ourselves back in the pool and release anybody who is waiting */
+                                idleThreads[numIdleThreads++] = this;
+                                ThreadPool.this.notifyAll();
+                            }
+                    }
                     try {
                         synchronized(this) { while (runnable==null) wait(); }
                         runnable.run();
                     } catch (Exception e) { Log.error(this, e); }
                     runnable = null;
-                    synchronized(ThreadPool.this) {
-                        /* if the idle array is full, just let ourselves die */
-                        if (numIdleThreads > minIdleThreads && numThreads > minThreads) return;
-                        /* otherwise put ourselves back in the pool and release anybody who is waiting */
-                        idleThreads[numIdleThreads++] = this;
-                        ThreadPool.this.notifyAll();
-                    }
                 }
             } finally {
-                numThreads--;
+                synchronized(ThreadPool.this) {
+                    numThreads--;
+                }
             }
         }
     }