// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.LinkedList;

public class ThreadPool {
    private LinkedList queue;
    private ThreadWorker[] t;
    public ThreadPool(int nthreads) {
        queue = new LinkedList();
        t = new ThreadWorker[nthreads];
        for (int i = 0; i < t.length; i++) {
            t[i] = new ThreadWorker(queue);
            t[i].start();
        }
    }
    public void addTask(Runnable r) {
        synchronized (queue) {
            queue.add(r);
            queue.notify();
        }
    }
    public void stop() {
        for (int i = 0; i < t.length; i++) {
            t[i].finish();
        }
        for (int i = 0; i < t.length; i++) {
            try {
                t[i].join();
            } catch (InterruptedException e) {
                // should never happend
            }
        }
    }
    public int queueSize() {
        int n;
        synchronized (queue) {
            n = queue.size();
        }
        return n;
    }
}

class ThreadWorker extends Thread {
    private LinkedList queue;
    private boolean done;
    public ThreadWorker(LinkedList queue) {
        this.queue = queue;
        done = false;
    }
    public void run() {
        while (!done) {
            Runnable r = null;
            synchronized (queue) {
                if (queue.size() == 0) {
                    try {
                        queue.wait(10000);
                    } catch (InterruptedException e) {
                        // should never happend
                    }
                }
                if (queue.size() > 0) {
                    r = (Runnable) queue.removeFirst();
                }
            }
            if (r != null) {
                try {
                    r.run();
                } catch (RuntimeException e) {
                    // do not stop
                }
            }
        }
    }
    public void finish() {
        done = true;
    }
}
