-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTracker.java
82 lines (73 loc) · 2.59 KB
/
Tracker.java
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
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by yizhiw on 7/12/2017.
*/
public class Tracker {
Map<String, List<Integer>> hostPool;
public Tracker() {
hostPool = new HashMap<String,List<Integer>>();
}
public String allocate(String hostType) {
List<Integer> list = hostPool.get(hostType);
if (list == null) {
// new type
list = new LinkedList<Integer>();
list.add(1);
// update the host pool
hostPool.put(hostType, list);
return (hostType + "1");
} else {
// existing type, find the next number, insert into the list
ServerCounter counter = new ServerCounter();
int next = counter.nextServerNumber(list);
// add into the list
list.add(next);
return (hostType + next);
}
}
public void deallocate(String server) {
if (server == null) {
return;
}
// get the host type and server number from the passing server name
String hostType = "";
int serverID = 0;
for (int i = 0; i < server.length(); i++) {
char ch = server.charAt(i);
if ((ch >= '0') && (ch <= '9')) {
hostType = server.substring(0, i);
serverID = Integer.parseInt(server.substring(i, server.length()));
}
}
List<Integer> list = hostPool.get(hostType);
if (list == null) {
return;
} else {
// remove serverID from the list
for (int i = 0; i < list.size(); i++) {
if (serverID == list.get(i)) {
list.remove(i);
return;
}
}
}
}
public static void main(String[] args) {
Tracker tacker = new Tracker();
System.out.println(tacker.allocate("apibox"));
System.out.println(tacker.allocate("apibox"));
System.out.println(tacker.allocate("apibox"));
System.out.println(tacker.allocate("sitebox"));
System.out.println(tacker.allocate("sitebox"));
System.out.println(tacker.allocate("sitebox"));
System.out.println(tacker.allocate("sitebox"));
tacker.deallocate("apibox1");
System.out.println(tacker.allocate("apibox"));
tacker.deallocate("sitebox3");
tacker.deallocate("sitebox2");
System.out.println(tacker.allocate("sitebox"));
}
}