-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeartbeats.java
More file actions
110 lines (81 loc) · 2.2 KB
/
Heartbeats.java
File metadata and controls
110 lines (81 loc) · 2.2 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import java.util.Random;
import java.net.InetSocketAddress;
/**
* Heartbeats thread periodically check if predecessor and successor alive, and randomly check
* a key of finger table is correct or not.
*
*
*/
public class Heartbeats extends Thread{
private Node local;
Random random;
boolean alive;
public Heartbeats(Node node) {
local = node;
alive = true;
random = new Random();
}
// num = random number from 1 to 32 //
@Override
public void run() {
while (alive) {
int interval = 200;
checkPredecessor();
checkSuccessor();
checkFingerTable();
// sleep //
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* randomly check a key of finger table to see if it's the right key
*/
private void checkFingerTable(){
int num = random.nextInt(31) + 2;
InetSocketAddress ithFinger = local.findSuccessor(Helper.ithStart(local.getId(), num));
local.updateFingers(num, ithFinger);
}
/**
* check if predecessor is alive
*/
private void checkPredecessor() {
InetSocketAddress pred = local.getPredecessor();
if(pred!=null){
String rev = Helper.sendRequest(pred,"KEEP");
if(rev == null){
local.setPredecessor(null);
}
}
}
/**
* check and update successor
*/
private void checkSuccessor(){
InetSocketAddress suc = local.getSuccessor();
// fill successor if it's null
if(suc == null || suc.equals(local.getAddress())){
local.updateFingers(-3,null);
suc = local.getSuccessor();
}
if (suc != null && !suc.equals(local.getAddress())) {
// delete successor if the connection fail
InetSocketAddress pre = Helper.requestAddress(suc,"YOURPRE");
if(pre == null) local.updateFingers(-1,null);
// update successor if the successor's predecessor closer to current node
else if(!pre.equals(suc)){
long localID = Helper.hashSocketAddress(local.getAddress());
long preRID = Helper.computeRelativeId(Helper.hashSocketAddress(pre),localID);
long sucRID = Helper.computeRelativeId(Helper.hashSocketAddress(suc),localID);
if(preRID > 0 && sucRID > preRID) local.updateFingers(1,pre);
}
else local.notify(suc);
}
}
public void toDie() {
alive = false;
}
}