-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventLoop.java
More file actions
96 lines (59 loc) · 1.58 KB
/
Copy pathEventLoop.java
File metadata and controls
96 lines (59 loc) · 1.58 KB
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
26
27
28
29
30
31
32
33
34
35
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package tinyTCPServer.net;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import tinyTCPServer.net.Poller;
;
public class EventLoop implements Task {
private Poller poller_;
private MessageProcessor msgProcessor_ = new EchoMessageProcessor();
private final Queue<Task> taskQueue = new ConcurrentLinkedQueue<Task>();
public EventLoop() throws IOException {
this.poller_ = new Poller();
}
public void setMessageProcessor(MessageProcessor msgProcessor) {
this.msgProcessor_ = msgProcessor;
}
public void execute() {
for (;;) {
try {
this.poller_.poll();
this.poller_.processActiveChannels(this.msgProcessor_);
processPendingEventLoopTaskQueue();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
public void processPendingEventLoopTaskQueue() {
for (;;) {
final Task task = taskQueue.poll();
if (task == null) {
break;
}
task.execute();
}
}
public void injectNewTask(Task task) {
// thread safe
taskQueue.offer(task);
this.poller_.wakeUp();
}
public void assignMonitorChannel(final SocketChannel acceptedSocketChannel) {
Task task = new Task() {
public void execute() {
poller_.registerChannel(acceptedSocketChannel);
}
};
this.injectNewTask(task);
}
}