1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.netty.channel.socket.nio;
18
19 import java.util.concurrent.Executor;
20 import java.util.concurrent.atomic.AtomicInteger;
21
22 import org.jboss.netty.channel.socket.Worker;
23 import org.jboss.netty.util.ExternalResourceReleasable;
24 import org.jboss.netty.util.internal.ExecutorUtil;
25
26
27
28
29
30 public abstract class AbstractNioWorkerPool<E extends AbstractNioWorker>
31 implements WorkerPool<E>, ExternalResourceReleasable {
32
33 private final AbstractNioWorker[] workers;
34 private final AtomicInteger workerIndex = new AtomicInteger();
35 private final Executor workerExecutor;
36
37
38
39
40
41
42
43
44 AbstractNioWorkerPool(Executor workerExecutor, int workerCount) {
45 if (workerExecutor == null) {
46 throw new NullPointerException("workerExecutor");
47 }
48 if (workerCount <= 0) {
49 throw new IllegalArgumentException(
50 "workerCount (" + workerCount + ") " +
51 "must be a positive integer.");
52 }
53 workers = new AbstractNioWorker[workerCount];
54
55 for (int i = 0; i < workers.length; i++) {
56 workers[i] = createWorker(workerExecutor);
57 }
58 this.workerExecutor = workerExecutor;
59 }
60
61
62
63
64
65
66
67
68 protected abstract E createWorker(Executor executor);
69
70 @SuppressWarnings("unchecked")
71 public E nextWorker() {
72 return (E) workers[Math.abs(workerIndex.getAndIncrement() % workers.length)];
73 }
74
75
76 public void releaseExternalResources() {
77 ExecutorUtil.terminate(workerExecutor);
78 for (AbstractNioWorker worker: workers) {
79 worker.releaseExternalResources();
80 }
81 }
82
83 }