Skip to content

Commit 1ac02d2

Browse files
committed
Add TT2.java
1 parent cbaa0d5 commit 1ac02d2

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Miscellaneous/TT2.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import java.util.*;
2+
3+
public class TT2 {
4+
public class Task {
5+
public String name;
6+
public int weight;
7+
public long TTL;
8+
9+
public Task(String n, int w, long ttl) {
10+
this.name = n;
11+
this.weight = w;
12+
this.TTL = currentTime + ttl;
13+
}
14+
}
15+
16+
public class Server {
17+
public char name;
18+
public int totalWeight;
19+
public PriorityQueue<Task> tasks;
20+
21+
public Server(char name) {
22+
this.name = name;
23+
this.totalWeight = 0;
24+
tasks = new PriorityQueue<>((t1, t2) -> t1.ttl - t2.ttl);
25+
}
26+
27+
public void addTask(String taskName, int taskWeight, int taskTTL) {
28+
invalidateTasks();
29+
Task t = new Task(taskName, taskWeight, taskTTL);
30+
tasks.add(t);
31+
totalWeight += t.weight;
32+
}
33+
34+
private void invalidateTasks() {
35+
while (!tasks.isEmpty() && currentTime >= tasks.peek().ttl) {
36+
tasks.poll();
37+
}
38+
}
39+
}
40+
41+
public class LoadBalancer {
42+
public PriorityQueue<Server> servers;
43+
44+
public LoadBalancer() {
45+
servers = new PriorityQueue<>((s1, s2) -> s1.totalWeight - s2.totalWeight);
46+
}
47+
48+
public boolean addServer(char serverName) {
49+
Server s = new Server(serverName);
50+
servers.add(s);
51+
return true;
52+
}
53+
54+
public boolean addTask(String taskName, int taskWeight, int taskTTL) {
55+
servers.peek().addTask(taskName, taskWeight, taskTTL);
56+
return true;
57+
}
58+
}
59+
60+
public static void main(String[] args) {
61+
LoadBalancer lb = new LoadBalancer();
62+
for (char serverName : serverList) {
63+
lb.addServer(serverName);
64+
}
65+
66+
for (int taskWeight : taskList) {
67+
lb.addTask("", taskWeight, TTL);
68+
}
69+
70+
return;
71+
}
72+
}

0 commit comments

Comments
 (0)