s LearnSqueak.com

ALGORITHMS · CACHING

Build an LRU cache: keep the recently used results

Build a bounded Smalltalk cache with read-through loading, trace hits and evictions in Squeak, and test nil values, zero capacity and failed loaders.

10 exact cases30 assertions8-request native trace

Start with a disposable learning image

Squeak 6.1 · Intermediate · About 30 minutes

A cache avoids repeating work by remembering an answer. A bounded cache also needs a rule for making room. In this tutorial, you will build that rule yourself, watch every change, and check the awkward cases rather than relying on a lucky demonstration.

Outcome: a self-contained Workspace experiment with a fixed entry limit, read-through loading, least-recently-used eviction, and visible hit/miss counts. No packages, networking, or class installation are required.

Before you start: be comfortable with temporary variables, blocks, and ifTrue:ifFalse:. A Dictionary stores answers; an OrderedCollection stores their recency. This is an algorithm lesson, not another general tour of collections.

Use a copy of your Squeak image. These are complete Workspace expressions, not chunk-format class definitions. Open each download as text and evaluate its full contents in Workspace; do not file it in as a package. Review blocks and closures, collections, and your first Dictionary if needed.

Download the complete 30-assertion experiment · Download the optional native visual trace · Read the actual native test results

Native-only: this lesson does not add a SqueakJS playground launcher. The cache uses no network access, persistence, timer, or installed classes. The visual window uses a fixed 1000 × 560 layout; keep that size or larger and close it normally when done.

1. Decide what “recently used” means

Imagine three spaces on a shelf. Every time you use an item, move its label to the right-hand end. When a new item needs a full shelf, remove the leftmost label and its item.

Our order runs least recently used → most recently used. A successful lookup changes that order even though it does not add an entry. That is what distinguishes LRU from a first-in, first-out queue. LRU is a replacement policy, not a prediction that the oldest result will never be needed again.

We will cache squares of numbers so that answers are easy to check. Squaring is deliberately cheap: this demonstrates avoided loader calls, not a speed improvement. Real candidates might be an expensive calculation whose answer remains valid for a known key.

A request is a hit if its key is already stored. Otherwise it is a miss, and the supplied loader block computes an answer. The key, not the loader block, identifies the cached result. Supplying a different loader for a key that is still cached does not update its answer.

NATIVE SQUEAK CAPTURE
The empty native LRU visualizer with three slots and zero counters
A genuine Squeak Morphic window before the first request. The order is always oldest on the left.

2. Remember one answer

Open a Workspace. Select this entire block and choose print it from the text menu:

Workspace · select the entire block, then Print it
| values |
values := Dictionary new.
values at: 6 put: 36.
values at: 6

Expected answer: 36.

The number 6 is the key; 36 is its value. Our cache will ask whether a key exists before deciding to compute. It must not ask merely whether the value is nil, because nil can itself be a legitimate cached answer. The official Dictionary reference describes the key/value model.

NATIVE SQUEAK CAPTURE
Squeak Workspace returns 36 after retrieving Dictionary key 6
Native Workspace Print it result for the first complete example.

3. Keep recency separate from values

Run this as a new, complete selection:

Workspace · select the entire block, then Print it
| recency |
recency := OrderedCollection new.
recency addLast: 6; addLast: 8; addLast: 10.
recency remove: 6.
recency addLast: 6.
recency asArray

Expected answer: #(8 10 6).

The contents have not changed, but their order has. Using 6 makes it newest. Removing the old occurrence first is essential: simply adding 6 again would create duplicate labels. The output is an Array snapshot of the order, not the Dictionary's enumeration order. The official OrderedCollection reference covers explicit insertion order and end operations.

NATIVE SQUEAK CAPTURE
Squeak Workspace returns recency order 8 10 6
Native Workspace result: the used key 6 moves to the most-recent end.

4. Run the complete experiment

Open a Transcript as well as your Workspace. Paste this whole program into the Workspace, select all of it, and choose print it. Do not run only a middle fragment: the temporary variables and blocks belong to this complete selection. It is safe to repeat the whole program; each run starts with fresh collections.

Workspace · select the entire block, then Print it
| capacity values recency hits misses loads reset fetch |

reset := [:limit |
    (limit isInteger and: [limit >= 0])
        ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
    capacity := limit.
    values := Dictionary new.
    recency := OrderedCollection new.
    hits := 0.
    misses := 0.
    loads := 0].

fetch := [:key :load |
    (values includesKey: key)
        ifTrue: [
            hits := hits + 1.
            recency remove: key.
            recency addLast: key.
            values at: key]
        ifFalse: [
            | answer |
            misses := misses + 1.
            answer := load value.
            capacity > 0 ifTrue: [
                values size = capacity ifTrue: [
                    values removeKey: recency removeFirst].
                values at: key put: answer.
                recency addLast: key].
            answer]].

reset value: 3.
#(6 8 10 6 12 10 8 12) do: [:key |
    | answer |
    answer := fetch value: key value: [
        loads := loads + 1.
        key squared].
    Transcript
        show: 'key='; show: key printString;
        show: ' value='; show: answer printString;
        show: ' order='; show: recency asArray printString;
        show: ' hits='; show: hits printString;
        show: ' misses='; show: misses printString; cr].

{hits. misses. loads. recency asArray}

Expected final answer:

#(3 5 5 #(10 8 12))

The first three numbers are hits, misses, and actual loader calls. The final Array is the remaining order, oldest first. The Transcript should show:

key=6 value=36 order=#(6) hits=0 misses=1
key=8 value=64 order=#(6 8) hits=0 misses=2
key=10 value=100 order=#(6 8 10) hits=0 misses=3
key=6 value=36 order=#(8 10 6) hits=1 misses=3
key=12 value=144 order=#(10 6 12) hits=1 misses=4
key=10 value=100 order=#(6 12 10) hits=2 misses=4
key=8 value=64 order=#(12 10 8) hits=2 misses=5
key=12 value=144 order=#(10 8 12) hits=3 misses=5

The complete program, final summary and all eight visual states passed native Squeak 6.1 checks.

Read the Smalltalk without losing the algorithm

  • reset and fetch hold blocks, which are pieces of code we can run later.
  • fetch value: key value: [ ... ] passes two arguments: a key and a zero-argument loader block. Only the miss branch sends value to that loader.
  • The last expression in each branch is the answer returned by that branch. Both branches answer the cached or freshly loaded value.
  • loads belongs to our demonstration. The loader increments it, so it independently reveals whether work ran. The cache itself manages hits and misses.
  • The final braces construct an Array containing the four summary values. They do not print the whole cache or expose its Dictionary.
NATIVE SQUEAK CAPTURE
Native LRU window after keys 6 8 and 10 fill all three slots
After the first three requests, all slots are occupied and there have been three loader calls.

5. Explain the first hit

The first three requests fill the cache: 6, then 8, then 10. Request four asks for 6 again.

The includesKey: test succeeds. The hit branch increments hits, removes 6 from its old position, appends it at the newest end, and returns the existing value. The loader is untouched. The order becomes 8, 10, 6 while the cache still holds three entries.

This is the defining update. If you remove the two recency-changing lines from the hit branch, the example no longer implements LRU. With insertion order left unchanged, the next full-cache miss would discard 6 even though it was just used.

Check your understanding: before continuing, predict which key will disappear when 12 arrives. It is 8, not 6 and not the numerically smallest value by rule. The decision comes from recency, not sorting.

NATIVE SQUEAK CAPTURE
Native LRU hit on key 6 moves it after keys 8 and 10
Request 4 is a hit. Key 6 moves right; the loader-call count remains 3.

6. Make room on a miss, but only after loading succeeds

When 12 arrives, the miss branch first calls the loader. Only after it obtains an answer does it check capacity and remove the oldest entry if necessary. It then stores the new answer and puts the new key at the recent end.

The order of these operations matters. If a loader raises an error, it should not destroy a previously useful entry just to make room for a result that never arrived. In this version the failed attempt still counts as a miss, but it does not change stored entries or recency. The error is allowed to propagate to the caller; the verification script catches a deliberate error only to check this behavior.

At zero capacity, requests still return loaded answers. Nothing is retained, so every request is a miss. The outer capacity > 0 check prevents trying to remove a first element from an empty order list.

The reset block rejects negative, fractional, or nonnumeric capacities before changing the current cache. Zero is intentional. Changing capacity here means resetting everything, not resizing an existing cache in place.

NATIVE SQUEAK CAPTURE
Native LRU miss for 12 evicts key 8 and keeps 10 6 12
Request 5 is a miss. Only after loading 144 does the cache evict key 8.

7. Check the boundary cases

The downloadable companion lru-cache.st is a complete Workspace script containing the same implementation, the trace, and 30 assertions. Open it as text, select its entire contents, and do it. Do not install it as a class file-out. If the specified checks pass, it prints LRU checks passed: 30 and answers 30. A failed check raises an error with a label.

The checks are designed to establish the following, not merely to print an attractive trace:

ExperimentExpected behavior
The eight-request trace3 hits, 5 misses, 5 loader calls, final order 10, 8, 12
Cache a nil answer twiceOne load; the second request is a hit and still answers nil
Capacity 0, same key twiceTwo loads and no retained entries
Capacity 1, request 6, 8, 6Three misses; only 6 remains
Two equal but separately copied String keysOne cache entry and a hit on the second request
Loader failure while fullExisting keys and recency survive; the failed key is absent
Capacity −1, 1.5, or a StringRejected without replacing the current cache
Capacity 2, request 6, 8, 10, 6, 8, 10Six misses; repeated scanning can defeat this policy

Three invariants make the implementation understandable: the two collections describe the same keys; each key appears once in recency; and the number of retained entries never exceeds the chosen capacity. The verification file checks consistency in the main trace and exercises the special cases above. It is not an exhaustive proof of every possible input or scheduling pattern.

NATIVE SQUEAK CAPTURE
Native LRU request 8 evicts key 6 and leaves keys 12 10 8
At request 7, key 8 must be loaded again because it was evicted earlier.

8. Know where this version stops

It optimizes clarity, not the recency operations. Finding and removing a key from the OrderedCollection can take linear work in the cache size. Do not advertise this as an O(1) LRU cache. A more involved version can pair a key-to-node dictionary with a doubly linked list to move a known node directly. This tutorial deliberately leaves that representation for another lesson.

An entry limit is not a byte limit. Three large objects may retain much more memory than three small ones. The cache stores references; changing a cached mutable object changes the object seen by later callers. Keys must keep stable equality and hash behavior while stored. Immutable numeric keys keep this demonstration uncomplicated.

Recency is not freshness. There is no expiration time, invalidation message, or external-data refresh. If a result changes, using the same key can return an old answer. Resetting discards everything. A production design should make its freshness policy explicit. The official Python cache documentation is a useful comparison for bounded memoization and its retained references, not a specification for this Smalltalk implementation.

The operations are not synchronized. Use this single-process demonstration sequentially. Do not let a loader recursively call this same cache or reset it; reentrant loading and concurrent processes require additional design. There is also no cancellation protocol, persistent storage, or independent put: operation.

Do not cache work whose effects must happen every time. A cache hit deliberately skips its loader. A loader that writes a file, charges a payment, or returns a fresh random value has different semantics when skipped. Use a stable key for all information that influences a reusable answer.

Two small experiments

  1. Change the demonstration capacity from 3 to 2. Predict the new trace before running it. Do not assume a larger hit rate merely because the numbers repeat.
  2. Change the request sequence to the same key eight times. With positive capacity, expect one miss followed by seven hits. Then compare zero capacity.

The important result is not just “a value came back.” You can now explain which work was skipped, why one entry was evicted, and which assumptions keep that decision correct.

NATIVE SQUEAK CAPTURE
Final native LRU state: 3 hits 5 misses and order 10 8 12
The eighth request is a hit. These counters count loader calls, not elapsed-time performance.

9. Advance the native visual trace yourself

Open the visual-trace download as text. Paste the entire expression below into a new Workspace, select it all, and choose Do it. A separate Morphic window opens with an empty cache. This is the same reset/fetch implementation as the earlier example, with drawing and controls added around it.

  1. Press Next request three times to fill the cache.
  2. Predict the next order, then press it once: the hit moves 6 from left to right without loading it again.
  3. Press it again: the miss for 12 evicts 8.
  4. Continue to request 8. Another press makes no change; there is no hidden loop.
  5. Reset discards all entries and counters, returning to the initial state.

Each card is drawn from the current Dictionary and recency list after the request completes. Hits are not inferred from colors: the status line and counters say exactly which branch ran. These controls retain blocks after the Workspace evaluation returns, a practical use of closures. Close the window when finished.

NATIVE SQUEAK CAPTURE
LRU visualizer ready to replay the eight cache requests
Replay of nine genuine Squeak imageForm captures: the initial state and eight actual button actions. It is a captured-state sequence, not mouse footage.
Show the complete runnable visual trace
Workspace · select the complete visual trace, then Do it
"Run this whole Workspace expression with Do it. No classes are installed.
Next request advances once; Reset makes a fresh three-entry cache.
The answer is {window. next block. reset block. snapshot block}, for inspection."
| capacity values recency hits misses loads reset fetch sequence index lastKey lastAnswer lastHit evicted window panel area label render advance restart snapshot nextButton resetButton |
reset := [:limit |
    (limit isInteger and: [limit >= 0])
        ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
    capacity := limit.
    values := Dictionary new.
    recency := OrderedCollection new.
    hits := 0. misses := 0. loads := 0].
fetch := [:key :load |
    (values includesKey: key)
        ifTrue: [
            hits := hits + 1.
            recency remove: key.
            recency addLast: key.
            values at: key]
        ifFalse: [
            | answer |
            misses := misses + 1.
            answer := load value.
            capacity > 0 ifTrue: [
                values size = capacity ifTrue: [
                    values removeKey: recency removeFirst].
                values at: key put: answer.
                recency addLast: key].
            answer]].
sequence := #(6 8 10 6 12 10 8 12).
panel := Morph new color: (Color fromString: '#F3F7FA').
window := SystemWindow new setLabel: 'LRU cache / LearnSqueak'.
window addMorph: panel fullFrame: (LayoutFrame fractions: (0@0 corner: 1@1)).
window openInWorld; extent: 1000@560; position: 20@20.
area := Morph new color: panel color; extent: 940@415.
panel addMorph: area.
area position: panel position + (20@20).
label := [:string :point :size :shade |
    | text |
    text := StringMorph contents: string font: (StrikeFont familyName: 'DejaVu Sans' pointSize: size).
    text color: shade; position: area position + point.
    area addMorph: text].
render := [
    area removeAllMorphs.
    label value: 'Least recent  ->  Most recent' value: 10@8 value: 23 value: Color black.
    label value: ('Requests: ', sequence printString) value: 10@47 value: 18 value: Color darkGray.
    label value: ('Completed: ', index printString, ' / 8    Capacity: 3') value: 10@82 value: 18 value: Color darkGray.
    1 to: 3 do: [:slot |
        | box key shade |
        shade := slot <= recency size
            ifTrue: [Color fromString: '#D1E7F1']
            ifFalse: [Color fromString: '#E7ECEF'].
        box := BorderedMorph new color: shade; borderWidth: 2; borderColor: (Color fromString: '#537386'); extent: 278@120.
        area addMorph: box.
        box position: area position + (((slot - 1) * 305 + 10)@134).
        slot <= recency size
            ifTrue: [
                key := recency at: slot.
                label value: ('Key ', key printString) value: (((slot - 1) * 305 + 28)@151) value: 25 value: Color black.
                label value: ('Value ', (values at: key) printString) value: (((slot - 1) * 305 + 28)@204) value: 20 value: Color black]
            ifFalse: [label value: 'Empty slot' value: (((slot - 1) * 305 + 28)@173) value: 21 value: Color darkGray]].
    label value: ('Hits: ', hits printString, '     Misses: ', misses printString, '     Loader calls: ', loads printString)
        value: 10@279 value: 20 value: Color black.
    index = 0
        ifTrue: [label value: 'Press Next request. A hit moves its key to the right.' value: 10@325 value: 18 value: Color darkGray]
        ifFalse: [
            label value: ('Request ', lastKey printString, ' -> ', lastAnswer printString, '     ', (lastHit ifTrue: ['HIT: loader skipped'] ifFalse: ['MISS: loader ran']))
                value: 10@325 value: 20 value: Color black.
            label value: (evicted isNil ifTrue: ['No eviction on this request.'] ifFalse: ['Evicted key ', evicted printString, ' from the least-recent end.'])
                value: 10@367 value: 18 value: Color darkGray].
    area changed].
advance := [
    index < sequence size ifTrue: [
        index := index + 1.
        lastKey := sequence at: index.
        lastHit := values includesKey: lastKey.
        evicted := (lastHit not and: [values size = capacity])
            ifTrue: [recency first] ifFalse: [nil].
        lastAnswer := fetch value: lastKey value: [loads := loads + 1. lastKey squared].
        render value]].
restart := [reset value: 3. index := 0. lastKey := nil. lastAnswer := nil. lastHit := false. evicted := nil. render value].
snapshot := [{index. hits. misses. loads. recency asArray. lastKey. lastAnswer. lastHit. evicted}].
nextButton := SimpleButtonMorph new label: 'Next request'; target: advance; actionSelector: #value; extent: 170@35.
resetButton := SimpleButtonMorph new label: 'Reset'; target: restart; actionSelector: #value; extent: 120@35.
panel addMorph: nextButton; addMorph: resetButton.
nextButton position: panel position + (30@465).
resetButton position: panel position + (220@465).
restart value.
{window. advance. restart. snapshot}

10. Verify the implementation, then extend it

The release checks executed all ten machine-readable cases, the standalone 30-assertion script, all eight native visual states, and the actual Next/Reset button actions in Squeak 6.1 build 23976. The test runner also checks that Next after the final request is a no-op. Every displayed executable code block is included in those native checks.

The visual captures are native Squeak-rendered window imageForms. They are not browser simulations, illustrations of invented output, or a claim of mouse-recorded footage. The source kit includes exact input/output cases and a Python reproduction runner; the runner needs a Squeak VM and matching image, creates a temporary private image, and writes captures/results beside itself. It never modifies the original image.

For a next exercise, add an explicit invalidation operation, specify whether it changes hit/miss counts, and write tests before updating the visualizer. To study the tradeoff behind this simple linear recency list, continue with linked lists. For honest speed comparisons, see measure first; fewer loader calls alone do not prove a faster program.

Primary API references: the official Squeak Terse Guide, Dictionary, and OrderedCollection. These document language and collection behavior, not evidence that this original implementation ran. The linked native results provide that execution evidence.