27/37
Part 5 of 6 · Both limitsLearn and do
Trace it out loud with a fake clock
The cache has capacity=2. Each entry shows its key, value and expires_at, oldest use first:
| t | Call, and what it returns | Entries after |
|---|---|---|
| 0 | put("a", 1, ttl=10) | a 1 10 |
| 0 | put("b", 2, ttl=3) | a 1 10 b 2 3 |
| 1 | get("a") returns 1 | b 2 3 a 1 10 |
| 4 | put("c", 3, ttl=10) | a 1 10 c 3 14 |
| 5 | put("d", 4) returns "a" | c 3 14 d 4 None |
| 6 | get("c") returns 3 | d 4 None c 3 14 |
| 14 | len(cache) returns 1 | d 4 None |
a evicted at 5
b expired at 3
c expires at 14
d never expires
0351014
seconds
Narrate the three interesting rows:
- At time 4 the cache is full, but
bexpired at 3. The sweep frees its slot, and nothing live is evicted. - At time 5 nothing has expired, so the least recently used entry,
a, is evicted, even though it had 5 seconds left. Its heap entry(10, 0, a)is now stale. - At time 14 the sweep pops
(10, 0, a), finds noastored, and skips it. Then it pops(14, 2, c)and deletesc, which expires at exactly 14. Onlydis left, and it never expires.
In the editor, write stale_count(entries, heap): how many heap entries no longer match what's stored. The editor holds the cache after put("d", 4): c and d are stored, and the heap still holds the entry of a.