1Request #1 gọi RateTable.Get("USD"): t.mu.RLock(), defer t.mu.RUnlock() rồi đọc t.rates["USD"]. Chỉ đọc nên không cần chặn reader khác như Mutex thường.Request #1 calls RateTable.Get("USD"): t.mu.RLock(), defer t.mu.RUnlock(), then reads t.rates["USD"]. It only reads, so it need not exclude other readers like a plain Mutex.
2Request #2 gọi Get("EUR") trong khi #1 vẫn giữ RLock. Hai lượt đọc không sửa map nên cùng vào được.Request #2 calls Get("EUR") while #1 still holds RLock. Neither read changes the map, so both enter together.
3Goroutine của StartRefresher nhận <-ticker.C (mỗi 5 phút) và gọi t.Refresh(ctx, fetch). Refresh gọi fetch(ctx) TRƯỚC khi lấy khoá, nên thời gian chờ mạng không chặn reader.The StartRefresher goroutine receives <-ticker.C (every 5 minutes) and calls t.Refresh(ctx, fetch). Refresh calls fetch(ctx) BEFORE taking the lock, so network latency does not block readers.
4Có bảng mới, Refresh gọi t.mu.Lock() và phải chờ #1, #2 nhả khoá. Request #3 gọi RLock lúc writer đang chờ nên cũng bị chặn: sync.RWMutex không để reader mới chen trước writer mãi.With fresh rates, Refresh calls t.mu.Lock() and waits for #1 and #2 to release. Request #3 calls RLock while the writer waits and blocks too: sync.RWMutex does not let new readers starve the writer.
5#1 và #2 RUnlock; writer có khoá độc quyền, gán t.rates = fresh rồi t.mu.Unlock(). Nếu fetch lỗi, Refresh trả err trước khi khoá và refresher chỉ log, vẫn phục vụ bảng cũ.#1 and #2 RUnlock; the writer gets exclusive access, assigns t.rates = fresh, then t.mu.Unlock(). If fetch fails, Refresh returns err before locking and the refresher only logs, keeping the old rates.
6Request #3 lấy được RLock và đọc JPY từ bảng mới hoàn chỉnh, không bao giờ thấy bảng đang ghi dở.Request #3 acquires RLock and reads JPY from the complete new table, never seeing a half-written one.
7Java ExchangeRateCache làm cùng việc: rate(currency) giữ lock.readLock(); refresh() chạy theo @Scheduled(fixedRate = 300_000), gọi fx.fetchAll() ngoài khoá rồi giữ writeLock() trong lúc rates.clear() và putAll(fresh).Java ExchangeRateCache does the same: rate(currency) holds lock.readLock(); refresh() runs on @Scheduled(fixedRate = 300_000), calls fx.fetchAll() outside the lock, then holds writeLock() across rates.clear() and putAll(fresh).
8Phương án không khoá: SnapshotTable.Get chỉ rates.Load() con trỏ map bất biến, Store(fresh) thay nguyên map một lần. Java SnapshotRateCache gán rates = Map.copyOf(fx.fetchAll()) vào biến volatile, còn lookups.merge đếm lượt tra theo từng key mà không cần khoá chung.The lock-free option: SnapshotTable.Get just does rates.Load() of an immutable map pointer, and Store(fresh) swaps the whole map at once. Java SnapshotRateCache assigns rates = Map.copyOf(fx.fetchAll()) to a volatile field, while lookups.merge counts per-key lookups without a global lock.