Run an LRU cache: hit, insert or evict the item that's gone unused the longest. 18 levels of eviction policy, recency and cache thrashing.
A cache is a small, close place for things used often, in front of a big, slow store. In Mrs. Wiwik's kitchen the cache is the shelf by the stove, and the store is the storeroom at the back. Every order needs one spice jar. If the jar is already on the shelf, that is a hit: just take it. If not, it is a miss: Mrs. Wiwik walks to the storeroom and brings the jar to the shelf. A full shelf has to send one jar back to the storeroom first. An LRU cache (Least Recently Used) picks the jar unused the longest.
If the shelf is full and an order needs a jar that is not on it, Mrs. Wiwik sends one jar back to the storeroom and puts the new one in its place. That is called eviction. LRU picks the jar unused the longest. How: look at the orders already served, and find the jar on the shelf whose last use came first. The jar sent back is not lost. It waits in the storeroom, and the next order that needs it means one more walk.
What people most often get wrong about LRU: a hit renews the time of use. A jar just taken from the shelf becomes the one used last, even if it was the first brought from the storeroom. So the jar going back is not the one that came first, but the one unused the longest. After every hit, the order changes.
There are other rules for choosing the jar that goes back. FIFO (First In, First Out) sends back the jar that came onto the shelf first, whenever it was last used: a hit changes nothing. LRU sends back the jar unused the longest: a hit renews that jar. Both guess the future from the past. Someone who knew every order in advance could send back the jar used again furthest ahead. That is Bélády's optimal (1966): no real cache knows the future, so it serves as a bound, not as a rule.
A cache is judged by how many orders the shelf serves: the hit ratio, the number of hits divided by the number of orders. Every miss is one walk to the storeroom. From this level on, the evening ends with tomorrow's orders. Count the walks from the shelf as you left it: a jar on the shelf when ordered needs no walk, a jar not there needs one, and remember that a jar brought in partway through the list can send another back.
Thrashing happens when the things used in turn outnumber the places in the cache. Under LRU, a loop one larger than the cache never hits: every item is always the one unused the longest just before it is needed again. Such a cache saves nothing and adds the work of moving things around. A computer out of memory does the same: memory pages go in and out of the disk all the time, and everything slows down.
And more, 18 levels in all.