summaryrefslogtreecommitdiff
path: root/same/src/main/java/com/orbekk/paxos/PaxosServiceImpl.java
blob: 3ecf5231d7785607e3e3b3fe49d06ab1adda1a67 (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
package com.orbekk.paxos;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class better be thread-safe.
 */
public class PaxosServiceImpl implements PaxosService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private int highestPromise = 0;
    private int highestAcceptedValue = 0;
    private String tag = "";

    public PaxosServiceImpl(String tag) {
        this.tag = tag;
    }

    @Override
    public synchronized int propose(String clientUrl,
            int proposalNumber) {
        if (proposalNumber > highestPromise) {
            logger.info(tag + "propose({}, {}) = accepted",
                    new Object[]{clientUrl, proposalNumber});
            highestPromise = proposalNumber;
            return highestPromise;
        } else {
            logger.info(tag + "propose({}, {}) = rejected " +
                    "(promised: {})",
                    new Object[]{clientUrl, proposalNumber,
                            highestPromise});
            return -highestPromise;
        }
    }

    @Override
    public synchronized int acceptRequest(String clientUrl,
            int proposalNumber) {
        if (proposalNumber == highestPromise) {
            logger.info(tag + "acceptRequest({}, {}) = accepted",
                    new Object[]{clientUrl, proposalNumber});
            highestAcceptedValue = proposalNumber;
            return highestAcceptedValue;
        } else {
            logger.info(tag + "acceptRequest({}, {}) = rejected " +
                    "(promise={})",
                    new Object[]{clientUrl, proposalNumber,
                            highestPromise});
            return -highestPromise;
        }
    }
}