blob: 37c125a19fd4e8c98f01b799ec4b9316c9e9f3b2 (
plain)
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
|
package pl.edu.mimuw.cloudatlas.agent;
import pl.edu.mimuw.cloudatlas.agent.messages.AgentMessage;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
/*
* The EventBus routes messages sent between Modules.
*/
public class EventBus implements Runnable {
private LinkedBlockingQueue<AgentMessage> events;
private HashMap<AgentMessage.AgentModule, Executor> executors;
void setEventBusReference() {
Iterator it = this.executors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<AgentMessage.AgentModule, Executor> executorEntry =
(Map.Entry<AgentMessage.AgentModule, Executor>) it.next();
executorEntry.getValue().setEventBus(this);
}
}
EventBus(HashMap<AgentMessage.AgentModule, Executor> executors) {
this.executors = executors;
setEventBusReference();
this.events = new LinkedBlockingQueue<AgentMessage>();
}
public void run() {
System.out.println("Event bus running");
while (!Thread.currentThread().interrupted()) {
try {
AgentMessage event = events.take();
routeMessage(event);
} catch (InterruptedException e) {
System.out.println("Event bus interrupted. Exiting loop.");
break;
}
}
}
public void routeMessage(AgentMessage msg) throws InterruptedException {
assert msg.getCorrectMessageType() == msg.getDestinationModule();
System.out.println("Event bus routing message");
executors.get(msg.getDestinationModule()).addMessage(msg);
}
public void addMessage(AgentMessage msg) throws InterruptedException {
assert msg.getCorrectMessageType() == msg.getDestinationModule();
this.events.put(msg);
}
}
|