- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathFairShareScheduling.java
65 lines (54 loc) · 1.79 KB
/
FairShareScheduling.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
packagecom.thealgorithms.scheduling;
importjava.util.HashMap;
importjava.util.Map;
/**
* FairShareScheduling allocates CPU resources equally among users or groups
* instead of individual tasks. Each group gets a proportional share,
* preventing resource hogging by a single user's processes.
*
* Use Case: Multi-user systems where users submit multiple tasks simultaneously,
* such as cloud environments.
*
* @author Hardvan
*/
publicfinalclassFairShareScheduling {
staticclassUser {
Stringname;
intallocatedResources;
inttotalWeight;
User(Stringname) {
this.name = name;
this.allocatedResources = 0;
this.totalWeight = 0;
}
voidaddWeight(intweight) {
this.totalWeight += weight;
}
}
privatefinalMap<String, User> users; // username -> User
publicFairShareScheduling() {
users = newHashMap<>();
}
publicvoidaddUser(StringuserName) {
users.putIfAbsent(userName, newUser(userName));
}
publicvoidaddTask(StringuserName, intweight) {
Useruser = users.get(userName);
if (user != null) {
user.addWeight(weight);
}
}
publicvoidallocateResources(inttotalResources) {
inttotalWeights = users.values().stream().mapToInt(user -> user.totalWeight).sum();
for (Useruser : users.values()) {
user.allocatedResources = (int) ((double) user.totalWeight / totalWeights * totalResources);
}
}
publicMap<String, Integer> getAllocatedResources() {
Map<String, Integer> allocation = newHashMap<>();
for (Useruser : users.values()) {
allocation.put(user.name, user.allocatedResources);
}
returnallocation;
}
}