7 Caching with generics

 

This chapter covers

  • Using generics in Go
  • Not using generics when they aren’t needed
  • Creating type constraints
  • Goroutines, parallelism, and concurrency
  • Race conditions
  • Adding mutexes
  • Learning some Go proverbs

Think back to your school days. Did you ever suddenly remember you had a homework assignment due the next day that you hadn’t even started? Maybe you phoned a friend and asked if they had the answer to question 2.b, just to get you a head start and allow you to spend more time on some other part of the homework. Teachers frowned on this kind of thing, of course.

7.1 A naive cache

7.1.1 Introduction to generics

7.1.2 Project initialization

7.1.3 Implementation

7.2 Introducing goroutines

7.2.1 What’s a goroutine?

7.2.2 How to launch a goroutine

7.2.3 Using channels to communicate that a goroutine has ended

7.2.4 Running goroutines and having a synchronization point

7.3 A more thread-safe cache

7.3.1 Using goroutines

7.3.2 Using t.Parallel()

7.3.3 Using go test -race .

7.3.4 Add a mutex

7.4 Possible improvements

7.4.1 Adding time to live

7.4.2 Add a maximum number of items in the cache

7.5 Common mistakes

7.5.1 When to use channels in a concurrency situation