m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/pl/edu/mimuw/cloudatlas/agent/Executor.java
blob: 6ebf6a6e91ec219bc1c34f65863b8859d0465617 (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
package pl.edu.mimuw.cloudatlas.agent;

import java.util.concurrent.LinkedBlockingQueue;

import pl.edu.mimuw.cloudatlas.agent.messages.AgentMessage;
import pl.edu.mimuw.cloudatlas.agent.modules.Module;

/*
 * Queues messages sent to a particular module and ensures they are eventually
 * handled.
 */
public class Executor implements Runnable {
    private Module module;
    private LinkedBlockingQueue<AgentMessage> events;
    private EventBus eventBus;

    public Executor(Module module) {
        this.module = module;
        this.module.setExecutor(this);
        this.events = new LinkedBlockingQueue<AgentMessage>();
    }

    public void run() {
        System.out.println("Executor " + this.module.toString() + " running");
        while (!Thread.currentThread().interrupted()) {
            try {
                AgentMessage event = events.take();
                System.out.println("Executor " + this.module.toString() + " passed message to handle");
                module.handle(event);
            } catch (InterruptedException e) {
                System.out.println("Executor interrupted. Exiting loop.");
                break;
            }
        }
    }

    public void addMessage(AgentMessage event) throws InterruptedException {
        events.put(event);
    }

    public void passMessage(AgentMessage event) throws InterruptedException {
        eventBus.addMessage(event);
    }

    public void setEventBus(EventBus eventBus) {
        this.eventBus = eventBus;
    }
}