Sobes.tech
Senior

What can lead to memory leaks in Go? What data synchronization types do you know in Go?

sobes.tech AI

Answer from AI

Memory leaks in Go can occur if objects remain reachable even though they are no longer needed, for example:

  • References to objects in global variables or closures.
  • Unfreed channels or goroutines that block and do not terminate.
  • Usage of slices or maps that grow and are not cleared.

Types of data synchronization in Go:

  • Mutex (sync.Mutex) — blocks access to shared data.
  • RWMutex (sync.RWMutex) — allows multiple readers or one writer.
  • WaitGroup (sync.WaitGroup) — waits for a group of goroutines to finish.
  • Atomic operations (sync/atomic) — for safe modification of variables without locks.
  • Channels (chan) — for data transfer between goroutines and synchronization.

Example of using Mutex:

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}