Build concurrent caches and pub-sub
Build concurrent caches and pub-sub
A cache retains completed values by key. Pub-sub distributes events to multiple subscribers. Both need concurrent access and capacity policies. This small cache stores immutable strings under an RWMutex; it has no expiration or size limit.
package main
import ( "fmt" "sync")
type Cache struct { mu sync.RWMutex data map[string]string}
func (c *Cache) Set(k, v string) { c.mu.Lock() defer c.mu.Unlock() if c.data == nil { c.data = make(map[string]string) } c.data[k] = v}func (c *Cache) Get(k string) (string, bool) { c.mu.RLock() defer c.mu.RUnlock() v, ok := c.data[k] return v, ok}func main() { var c Cache var wg sync.WaitGroup for _, k := range []string{"a", "b"} { wg.Add(1) go func(k string) { defer wg.Done(); c.Set(k, "value-"+k) }(k) } wg.Wait() a, _ := c.Get("a") _, ok := c.Get("missing") fmt.Println(a, ok)}The write lock protects initialization and updates; read locks protect lookup. The bool distinguishes absence from an empty string. Production caches require eviction, capacity and consistency policies. Separately locked Get and Set do not deduplicate misses.
Expected output:
value-a falseBroadcast with a slow-subscriber policy
package main
import ( "fmt" "sync")
type Broker struct { mu sync.Mutex subs map[chan string]struct{}}
func (b *Broker) Subscribe() <-chan string { b.mu.Lock() defer b.mu.Unlock() if b.subs == nil { b.subs = make(map[chan string]struct{}) } c := make(chan string, 1) b.subs[c] = struct{}{} return c}func (b *Broker) Publish(v string) int { b.mu.Lock() defer b.mu.Unlock() dropped := 0 for c := range b.subs { select { case c <- v: default: dropped++ } } return dropped}func (b *Broker) CloseAll() { b.mu.Lock() defer b.mu.Unlock() for c := range b.subs { close(c) delete(b.subs, c) }}func main() { var b Broker a := b.Subscribe() c := b.Subscribe() fmt.Println(b.Publish("news")) fmt.Println(b.Publish("later")) fmt.Println(<-a, <-c) b.CloseAll() _, ok := <-a fmt.Println(ok)}Each subscriber has a one-item channel. Full subscribers miss new messages, and Publish counts those drops. The lock serializes send and close. CloseAll closes current subscriptions, not the broker permanently. Individual unsubscribe, subscriber limits, replay and reliable delivery are omitted. Avoid blocking sends while holding this lock.
Expected output:
02news newsfalseTry it locally
Store an empty string under present; print presence flags for present and missing: true false.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 06: Build concurrent caches and pub-sub
Check the lesson objective before moving on.
Why one channel per subscriber?
What happens when this broker finds a full buffer?