-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem3_DNSCacheTTL.java
More file actions
98 lines (69 loc) · 2.25 KB
/
Problem3_DNSCacheTTL.java
File metadata and controls
98 lines (69 loc) · 2.25 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
import java.util.*;
class DNSEntry {
String domain;
String ipAddress;
long expiryTime;
DNSEntry(String domain, String ipAddress, long ttl) {
this.domain = domain;
this.ipAddress = ipAddress;
this.expiryTime = System.currentTimeMillis() + (ttl * 1000);
}
boolean isExpired() {
return System.currentTimeMillis() > expiryTime;
}
}
class DNSCache {
HashMap<String, DNSEntry> cache = new HashMap<String, DNSEntry>();
LinkedList<String> usageOrder = new LinkedList<String>();
int capacity = 5;
int hits = 0;
int misses = 0;
public String resolve(String domain) {
if (cache.containsKey(domain)) {
DNSEntry entry = cache.get(domain);
if (!entry.isExpired()) {
hits++;
usageOrder.remove(domain);
usageOrder.addLast(domain);
return "Cache HIT → " + entry.ipAddress;
} else {
cache.remove(domain);
usageOrder.remove(domain);
}
}
misses++;
String ip = queryUpstreamDNS(domain);
if (cache.size() >= capacity) {
String lru = usageOrder.removeFirst();
cache.remove(lru);
}
DNSEntry newEntry = new DNSEntry(domain, ip, 5);
cache.put(domain, newEntry);
usageOrder.addLast(domain);
return "Cache MISS → " + ip;
}
String queryUpstreamDNS(String domain) {
Random r = new Random();
return "172.217.14." + (200 + r.nextInt(50));
}
public void getCacheStats() {
int total = hits + misses;
double hitRate = 0;
if (total > 0) {
hitRate = (hits * 100.0) / total;
}
System.out.println("Hits: " + hits);
System.out.println("Misses: " + misses);
System.out.println("Hit Rate: " + hitRate + "%");
}
}
public class Problem3_DNSCacheTTL {
public static void main(String[] args) throws Exception {
DNSCache dns = new DNSCache();
System.out.println(dns.resolve("google.com"));
System.out.println(dns.resolve("google.com"));
Thread.sleep(6000);
System.out.println(dns.resolve("google.com"));
dns.getCacheStats();
}
}