summaryrefslogtreecommitdiff
path: root/jsonrpc/src/main/java/com/orbekk/same/SameState.java
blob: b2518c259046549b8ba577c7a8c3d7db8cc9d83d (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.orbekk.same;

import java.util.List;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The implementation of a 'Same' state.
 *
 * This class manages the current state of the Same protocol.
 */
public class SameState extends Thread {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private List<String> participants = new LinkedList<String>();
    private String currentState = "";
    private String networkName;
    private boolean stopped = false;

    /**
     * Queue for pending participants.
     */
    private List<String> pendingParticipants = new LinkedList<String>();

    public SameState(String networkName) {
        this.networkName = networkName;
    }

    public synchronized List<String> getParticipants() {
        return participants;
    }

    public String getNetworkName() {
        return networkName;
    }

    public String getCurrentState() {
        return currentState;
    }

    public synchronized void addParticipant(String url) {
        synchronized(this) {
            logger.info("Add pending participant: {}", url);
            pendingParticipants.add(url);
            notifyAll();
        }
    }

    private synchronized void handleNewParticipants() {
        for (String url : pendingParticipants) {
            logger.info("New participant: {}", url);
            participants.add(url);
        }
        pendingParticipants.clear();
    }

    public synchronized void run() {
        while (!stopped) {
            handleNewParticipants();
            try {
                wait(1000);
            } catch (InterruptedException e) {
                // Ignore interrupt in wait loop.
            }
        }
    }

    public synchronized void stopSame() {
        try {
            stopped = true;
            notifyAll();
            this.join();
        } catch (InterruptedException e) {
            logger.warn("Got InterruptedException while waiting for SameState " +
                    "to finish. Ignoring.");
        }
    }
}