01: package pygmy.core;
02:
03: import java.util.List;
04: import java.util.ArrayList;
05: import java.util.LinkedList;
06: import java.util.logging.Logger;
07: import java.util.logging.Level;
08:
09: public class ThreadPool {
10:
11: private static final Logger log = Logger.getLogger(ThreadPool.class
12: .getName());
13:
14: private List threads = new ArrayList();
15: private LinkedList queue = new LinkedList();
16:
17: public ThreadPool(int numberOfThreads) {
18: for (int i = 0; i < numberOfThreads; i++) {
19: if (log.isLoggable(Level.FINE)) {
20: log.fine("Creating thread " + i);
21: }
22: PooledThread thread = new PooledThread("Pooled Thread " + i);
23: thread.start();
24: threads.add(thread);
25: }
26: }
27:
28: public void execute(Runnable runnable) {
29: log.fine("Queueing runnable in thread pool.");
30: synchronized (queue) {
31: queue.add(runnable);
32: queue.notify();
33: }
34: }
35:
36: public void shutdown() {
37: for (int i = 0; i < threads.size(); i++) {
38: Thread thread = (Thread) threads.get(i);
39: thread.interrupt();
40: }
41: }
42:
43: protected class PooledThread extends Thread {
44: public PooledThread(String name) {
45: super (name);
46: setDaemon(true);
47: }
48:
49: public void run() {
50: try {
51: while (!isInterrupted()) {
52: waitForTask();
53: Runnable runnable = retrieveTask();
54: if (runnable != null) {
55: if (log.isLoggable(Level.FINE)) {
56: log.fine("Starting runnable on thread "
57: + Thread.currentThread().getName());
58: }
59: try {
60: runnable.run();
61: } catch (Exception e) {
62: log.log(Level.WARNING, e.toString(), e);
63: }
64: }
65: if (log.isLoggable(Level.FINE)) {
66: log.fine("Returning to thread pool "
67: + Thread.currentThread().getName());
68: }
69: }
70: } catch (InterruptedException e) {
71: log.log(Level.FINEST, Thread.currentThread().getName(),
72: e);
73: } finally {
74: log.log(Level.INFO, Thread.currentThread().getName()
75: + " is shutting down");
76: }
77: }
78:
79: private void waitForTask() throws InterruptedException {
80: synchronized (queue) {
81: if (queue.isEmpty()) {
82: queue.wait();
83: }
84: }
85: }
86:
87: private Runnable retrieveTask() {
88: Runnable runnable = null;
89: synchronized (queue) {
90: if (!queue.isEmpty()) {
91: runnable = (Runnable) queue.removeFirst();
92: }
93: }
94: return runnable;
95: }
96: }
97: }
|