1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.core.service;
21
22 import java.lang.reflect.Constructor;
23 import java.util.Arrays;
24 import java.util.concurrent.Executor;
25 import java.util.concurrent.ExecutorService;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.ThreadPoolExecutor;
28
29 import org.apache.mina.core.RuntimeIoException;
30 import org.apache.mina.core.session.AbstractIoSession;
31 import org.apache.mina.core.session.AttributeKey;
32 import org.apache.mina.core.session.IoSession;
33 import org.apache.mina.core.write.WriteRequest;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 public class SimpleIoProcessorPool<S extends AbstractIoSession> implements IoProcessor<S> {
80
81 private final static Logger LOGGER = LoggerFactory.getLogger(SimpleIoProcessorPool.class);
82
83
84 private static final int DEFAULT_SIZE = Runtime.getRuntime().availableProcessors() + 1;
85
86
87 private static final AttributeKey PROCESSOR = new AttributeKey(SimpleIoProcessorPool.class, "processor");
88
89
90 private final IoProcessor<S>[] pool;
91
92
93 private final Executor executor;
94
95
96 private final boolean createdExecutor;
97
98
99 private final Object disposalLock = new Object();
100
101
102 private volatile boolean disposing;
103
104
105 private volatile boolean disposed;
106
107
108
109
110
111
112
113 public SimpleIoProcessorPool(Class<? extends IoProcessor<S>> processorType) {
114 this(processorType, null, DEFAULT_SIZE);
115 }
116
117
118
119
120
121
122
123
124 public SimpleIoProcessorPool(Class<? extends IoProcessor<S>> processorType, int size) {
125 this(processorType, null, size);
126 }
127
128
129
130
131
132
133
134 public SimpleIoProcessorPool(Class<? extends IoProcessor<S>> processorType, Executor executor) {
135 this(processorType, executor, DEFAULT_SIZE);
136 }
137
138
139
140
141
142
143
144
145 @SuppressWarnings("unchecked")
146 public SimpleIoProcessorPool(Class<? extends IoProcessor<S>> processorType, Executor executor, int size) {
147 if (processorType == null) {
148 throw new IllegalArgumentException("processorType");
149 }
150
151 if (size <= 0) {
152 throw new IllegalArgumentException("size: " + size + " (expected: positive integer)");
153 }
154
155
156 createdExecutor = (executor == null);
157
158 if (createdExecutor) {
159 this.executor = Executors.newCachedThreadPool();
160
161 ((ThreadPoolExecutor) this.executor).setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
162 } else {
163 this.executor = executor;
164 }
165
166 pool = new IoProcessor[size];
167
168 boolean success = false;
169 Constructor<? extends IoProcessor<S>> processorConstructor = null;
170 boolean usesExecutorArg = true;
171
172 try {
173
174 try {
175 try {
176 processorConstructor = processorType.getConstructor(ExecutorService.class);
177 pool[0] = processorConstructor.newInstance(this.executor);
178 } catch (NoSuchMethodException e1) {
179
180 try {
181 processorConstructor = processorType.getConstructor(Executor.class);
182 pool[0] = processorConstructor.newInstance(this.executor);
183 } catch (NoSuchMethodException e2) {
184
185 try {
186 processorConstructor = processorType.getConstructor();
187 usesExecutorArg = false;
188 pool[0] = processorConstructor.newInstance();
189 } catch (NoSuchMethodException e3) {
190
191 }
192 }
193 }
194 } catch (RuntimeException re) {
195 LOGGER.error("Cannot create an IoProcessor :{}", re.getMessage());
196 throw re;
197 } catch (Exception e) {
198 String msg = "Failed to create a new instance of " + processorType.getName() + ":" + e.getMessage();
199 LOGGER.error(msg, e);
200 throw new RuntimeIoException(msg, e);
201 }
202
203 if (processorConstructor == null) {
204
205 String msg = String.valueOf(processorType) + " must have a public constructor with one "
206 + ExecutorService.class.getSimpleName() + " parameter, a public constructor with one "
207 + Executor.class.getSimpleName() + " parameter or a public default constructor.";
208 LOGGER.error(msg);
209 throw new IllegalArgumentException(msg);
210 }
211
212
213 for (int i = 1; i < pool.length; i++) {
214 try {
215 if (usesExecutorArg) {
216 pool[i] = processorConstructor.newInstance(this.executor);
217 } else {
218 pool[i] = processorConstructor.newInstance();
219 }
220 } catch (Exception e) {
221
222 }
223 }
224
225 success = true;
226 } finally {
227 if (!success) {
228 dispose();
229 }
230 }
231 }
232
233
234
235
236 public final void add(S session) {
237 getProcessor(session).add(session);
238 }
239
240
241
242
243 public final void flush(S session) {
244 getProcessor(session).flush(session);
245 }
246
247
248
249
250 public final void write(S session, WriteRequest writeRequest) {
251 getProcessor(session).write(session, writeRequest);
252 }
253
254
255
256
257 public final void remove(S session) {
258 getProcessor(session).remove(session);
259 }
260
261
262
263
264 public final void updateTrafficControl(S session) {
265 getProcessor(session).updateTrafficControl(session);
266 }
267
268
269
270
271 public boolean isDisposed() {
272 return disposed;
273 }
274
275
276
277
278 public boolean isDisposing() {
279 return disposing;
280 }
281
282
283
284
285 public final void dispose() {
286 if (disposed) {
287 return;
288 }
289
290 synchronized (disposalLock) {
291 if (!disposing) {
292 disposing = true;
293
294 for (IoProcessor<S> ioProcessor : pool) {
295 if (ioProcessor == null) {
296
297 continue;
298 }
299
300 if (ioProcessor.isDisposing()) {
301 continue;
302 }
303
304 try {
305 ioProcessor.dispose();
306 } catch (Exception e) {
307 LOGGER.warn("Failed to dispose the {} IoProcessor.", ioProcessor.getClass().getSimpleName(), e);
308 }
309 }
310
311 if (createdExecutor) {
312 ((ExecutorService) executor).shutdown();
313 }
314 }
315
316 Arrays.fill(pool, null);
317 disposed = true;
318 }
319 }
320
321
322
323
324
325 @SuppressWarnings("unchecked")
326 private IoProcessor<S> getProcessor(S session) {
327 IoProcessor<S> processor = (IoProcessor<S>) session.getAttribute(PROCESSOR);
328
329 if (processor == null) {
330 if (disposed || disposing) {
331 throw new IllegalStateException("A disposed processor cannot be accessed.");
332 }
333
334 processor = pool[Math.abs((int) session.getId()) % pool.length];
335
336 if (processor == null) {
337 throw new IllegalStateException("A disposed processor cannot be accessed.");
338 }
339
340 session.setAttributeIfAbsent(PROCESSOR, processor);
341 }
342
343 return processor;
344 }
345 }