1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package mk.fsgrep.util.thread;
26
27
28 import java.util.*;
29
30
31 /***
32 *
33 *
34 * @author Murali Krishnan
35 *
36 */
37 public class ThreadPool implements RunCallback {
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 private LinkedList<ThreadRunner> _available = new LinkedList<ThreadRunner>();
53 private String _name = "UNDEFINED";
54 private int _size = 0;
55
56
57
58
59
60
61 public ThreadPool(String pName, int pSize) {
62 _name = pName;
63 _size = pSize;
64
65 initialize();
66 }
67
68
69 public synchronized void initialize() {
70 for (int i = 0; i < getSize(); i++) {
71 String runnerName = getName() + "-" + i;
72 getAvailable().addLast(new ThreadRunner(runnerName, this));
73 }
74 }
75
76
77
78
79
80 protected LinkedList<ThreadRunner> getAvailable() {return _available;}
81 public String getName() {return _name;}
82 public int getSize() {return _size;}
83
84
85
86
87
88
89
90
91
92
93
94 protected synchronized ThreadRunner removeFirst() {
95 return getAvailable().isEmpty() ? null : getAvailable().removeFirst();
96 }
97
98 protected ThreadRunner getNextAvailable() {
99 ThreadRunner result = removeFirst();
100
101 while (result == null) {
102 try {
103 Thread.sleep(500);
104 } catch (InterruptedException ie) {
105
106 }
107
108 result = removeFirst();
109 }
110
111 return result;
112 }
113
114
115 protected synchronized int findNumberAvailable() {
116 int result = getAvailable().size();
117
118 return result;
119 }
120
121
122
123
124
125 public String toString() {
126 String result = "ThreadPool[\"" + getName() + "\", " +
127 findNumberAvailable() + "/" + getSize() + "]";
128
129 return result;
130 }
131
132
133 public void run(Runnable runnable) {
134 ThreadRunner runner = getNextAvailable();
135 runner.execute(runnable);
136 }
137
138
139 public void waitForCompletion() {
140 while (findNumberAvailable() > 0) {
141 try {
142 Thread.sleep(250);
143 } catch (InterruptedException ie) {
144
145 }
146 }
147 }
148
149
150
151
152
153 public synchronized void runFinished(ThreadRunner runner) {
154 getAvailable().addLast(runner);
155 }
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170 }