Time Thread A (Stats Reader) Thread B (Queue Worker)
---- ───────────────────────── ──────────────────────
1 START: immediate-stats()
2 cnt = q.size()
cnt = 5 ✓ [Reads queue size]
3 take!() ← DEQUEUE ITEM A
4 (process task A)
5 mark-complete!(A)
completed++ (3→4)
6 completed = completed.get()
completed = 4 ✓ [Reads counter]
7 enqueued = enqueued.get()
enqueued = 8 ✓ [Reads counter]
8 CALCULATE:
in-progress = (8 - 4) - 5
= 4 - 5
= -1 ✗✗✗ WRONG!
Between reading cnt=5 (step 2) and calculating the formula (step 8):
take!)completed)BEFORE (Bad):
in-progress = (enqueued - completed) - queue-size
Three separate reads:
1. queue.size() ← Can change between reads
2. completed counter ← Can change between reads
3. enqueued counter ← Can change between reads
Formula: ← Computed, error-prone
AFTER (Good):
in-progress = in-progress-counter.get()
Single operation:
1. Read atomic counter ← Atomic, cannot change mid-read
Direct value: ← Always correct
┌─────────────────┐
│ enqueued = 10 │
│ completed = 0 │
│ in-progress = 0 │
└────────┬────────┘
│
put! / queue
│
▼
┌─────────────────┐
┌──────→│ enqueued = 10 │◄──────┐
│ │ completed = 0 │ │
│ │ in-progress = 0 │ │
│ └────────┬────────┘ │
│ │ │
│ take!() ◄──┐ │
│ in-progress++ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ enqueued = 10 │ │
│ │ completed = 0 │ │
│ │ in-progress = 1 │ │
│ └────────┬────────┘ │
│ │ │
│ [PROCESSING] ◄──────────┐│
│ (user code) ││
│ │ ││
└────────────────┘ ││
mark-retry!() mark-complete!()
(back to queue) (task done)
in-progress-- in-progress--
│ │
└──────────────────────────────┘
1. INITIAL SETUP: Add counter
─────────────────────────────
(defn- initial-stats [^long count]
{:enqueued (AtomicLong. count)
:retried (AtomicLong. 0)
:completed (AtomicLong. 0)
:in-progress (AtomicLong. 0)}) ← NEW
▲
└─── Track in-progress directly
2. READ STATS: Use counter, not formula
─────────────────────────────────────
BEFORE:
(let [cnt (.size q) ← REMOVED: queue size read
completed (.get completed)
enqueued (.get enqueued)]
{:in-progress (- (- enqueued completed) cnt)})
▲
└─ REMOVED: Computed formula
AFTER:
{:enqueued (.get ^AtomicLong enqueued)
:retried (.get ^AtomicLong retried)
:completed (.get ^AtomicLong completed)
:in-progress (.get ^AtomicLong in-progress)} ← NEW: Direct reads, inline
▲
└─ All atomic operations, no intermediate bindings
3. DEQUEUE: Increment counter
───────────────────────────
take!()
(.poll q) ← Item leaves queue
(status! t :in-progress)
(increment in-progress-counter) ← NEW
▲
└─ Track that item is now being processed
4. COMPLETE: Decrement counter
────────────────────────────
mark-complete!()
(increment completed-counter)
(decrement in-progress-counter) ← NEW
▲
└─ Track that work is done
5. RETRY: Decrement counter
─────────────────────────
mark-retry!()
(increment retried-counter)
(decrement in-progress-counter) ← NEW
▲
└─ Track that work was not done
╔════════════════════════════════╦════════════════════════════════╗
║ BEFORE (Broken) ║ AFTER (Fixed) ║
╠════════════════════════════════╬════════════════════════════════╣
║ READS: ║ READS: ║
║ 1. queue.size() (non- ║ 1. in-progress.get() ║
║ 2. completed.get() atomic) ║ ║
║ 3. enqueued.get() ║ ✓ Atomic operation ║
║ ║ ✓ No race window ║
║ ✗ Race window exists ║ ║
║ ║ ║
╠════════════════════════════════╬════════════════════════════════╣
║ FORMULA: ║ DIRECT COUNTER: ║
║ (enqueued - completed) ║ in-progress ║
║ - queue.size() ║ ║
║ ║ ✓ Always accurate ║
║ ✗ Can produce negative ║ ✓ Never negative ║
║ ✗ Reconciles 3 variables ║ ✓ Single source of truth ║
║ ✗ Complex logic ║ ║
║ ║ ║
╠════════════════════════════════╬════════════════════════════════╣
║ UPDATES: ║ UPDATES: ║
║ None during stats read ║ ║
║ ║ take!() ║
║ During task operations: ║ in-progress++ ║
║ take!() ║ ║
║ (implicit: queue-size ▼) ║ mark-complete!() ║
║ ║ in-progress-- ║
║ mark-complete!() ║ ║
║ completed++ ║ mark-retry!() ║
║ (no effect on formula) ║ in-progress-- ║
║ ║ ║
║ mark-retry!() ║ ✓ Explicit tracking ║
║ retried++ ║ ✓ Race-free updates ║
║ (no effect on formula) ║ ║
║ ║ ║
║ ✗ Stats computed from side ║ ║
║ effects (unreliable) ║ ║
╚════════════════════════════════╩════════════════════════════════╝
Worker T1 Reader T2 Worker T3
───────── ──────── ─────────
take!()
q.size() = 5
START
cnt = 5
take!()
q.size() = 4
completed.get() = 1
mark-complete!()
completed = 2
enqueued.get() = 10
in-progress = (10-2)-5 = 3 ✓ OK this time
mark-complete!()
completed = 3
take!()
q.size() = 3
START (new read)
cnt = 3
take!()
q.size() = 2
completed.get() = 3
enqueued.get() = 10
in-progress = (10-3)-3 = 4 ✓ Happened to work
BUT COULD EASILY BE NEGATIVE!
Worker T1 Worker T2 Reader T3
───────── ───────── ────────
take!()
in-progress++ (now = 1)
START
in-progress.get() = 1 ✓
mark-complete!()
completed++
in-progress-- (now = 0)
take!()
in-progress++ (now = 1)
mark-complete!()
completed++
in-progress-- (now = 0)
take!()
in-progress++ (now = 1)
START (new read)
in-progress.get() = 1 ✓
ALWAYS CORRECT!
No race window!
Test: take! increments, mark-complete! decrements
BEFORE FIX:
queue setup
put!(task)
t = take!()
stats = stats()
assert stats[:in-progress] == 1 ← Sometimes FAILS!
(might be -1 due to race)
AFTER FIX:
queue setup
put!(task)
t = take!()
stats = stats()
assert stats[:in-progress] == 1 ← Always PASSES!
(atomic counter)
Test: 100 items, 10 concurrent readers, 10 concurrent workers
BEFORE FIX:
Run multiple times
Collect all in-progress values
Results (run to run varies due to races):
Run 1: in-progress values: [0, 1, 2, -1, 1, 0, 2, -2]
↑ ↑ WRONG!
Run 2: in-progress values: [0, 1, 1, 0, -1, 1]
↑ WRONG!
Run 3: in-progress values: [0, 1, 2, 1, 0, 1]
(happens to work)
AFTER FIX:
Run multiple times
Collect all in-progress values
Results (consistent due to atomic counter):
Run 1: in-progress values: [0, 1, 2, 1, 0, 1, 2, 1]
(all >= 0)
Run 2: in-progress values: [0, 1, 1, 0, 1, 2, 1, 0]
(all >= 0)
Run 3: in-progress values: [0, 1, 2, 1, 0, 1]
(all >= 0)
NEVER negative, ALWAYS consistent!
(defn- initial-stats [^long count]
{:enqueued (AtomicLong. count)
:retried (AtomicLong. 0)
- :completed (AtomicLong. 0)})
+ :completed (AtomicLong. 0)
+ :in-progress (AtomicLong. 0)})
(defn- immediate-stats [^LinkedBlockingQueue q {:keys [enqueued retried completed]}]
- (let [cnt (.size q)
- completed (.get ^AtomicLong completed)
- enqueued (.get ^AtomicLong enqueued)]
- {:enqueued enqueued
- :retried (.get ^AtomicLong retried)
- :completed completed
- :in-progress (- (- enqueued completed) cnt)}))
+ {:enqueued (.get ^AtomicLong enqueued)
+ :retried (.get ^AtomicLong retried)
+ :completed (.get ^AtomicLong completed)
+ :in-progress (.get ^AtomicLong in-progress)})
(status! t :in-progress)
+ (populate-stats! q-name)
+ (let [^AtomicLong counter (get-in @queue-name->stats [q-name :in-progress])]
+ (.incrementAndGet counter))
t)
(mark-complete! [_ q-name]
(mark-action!)
(populate-stats! q-name)
- (let [^AtomicLong retry-counter (get-in @queue-name->stats [q-name :completed])]
- (.incrementAndGet retry-counter)))
+ (let [^AtomicLong completed-counter (get-in @queue-name->stats [q-name :completed])
+ ^AtomicLong in-progress-counter (get-in @queue-name->stats [q-name :in-progress])]
+ (.incrementAndGet completed-counter)
+ (.decrementAndGet in-progress-counter)))
(mark-retry! [_ q-name]
(mark-action!)
(populate-stats! q-name)
- (let [^AtomicLong retry-counter (get-in @queue-name->stats [q-name :retried])]
- (.incrementAndGet retry-counter)))
+ (let [^AtomicLong retry-counter (get-in @queue-name->stats [q-name :retried])
+ ^AtomicLong in-progress-counter (get-in @queue-name->stats [q-name :in-progress])]
+ (.incrementAndGet retry-counter)
+ (.decrementAndGet in-progress-counter)))
| Aspect | Before | After |
|---|---|---|
| Mechanism | Computed formula | Direct counter |
| Reads | 3 non-atomic | 1 atomic |
| Race Window | YES (problem!) | NO (fixed!) |
| Can Go Negative | YES | NO |
| Complexity | High | Low |
| Performance | O(n) queue size read | O(1) atomic read |
| Correctness | Unreliable | Guaranteed |
Next Step: Follow the checklist in issue12-implementation-checklist.md to implement these changes!
Can you improve this documentation?Edit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |