CodeBlanks Logo Icon CodeBlanks

Concurrent GC

Learn how GC runs concurrently with the application.

Concurrent GC

Go's GC marks concurrently with the program. The world stops only for two brief moments (STW): when marking turns on and when it finishes. During marking about 25% of CPU goes to the GC; goroutines that allocate a lot are also forced to help through "mark assist".

GODEBUG=gctrace=1 ./app
# gc 12 @3.1s 2%: 0.03+1.2+0.02 ms clock, ...
#                 STW   conc. STW

The write barrier

If the program writes to a pointer field during marking, a short piece of code inserted by the compiler runs and paints the target object grey. Go uses a hybrid barrier (Yuasa + Dijkstra); thanks to it goroutine stacks don't need rescanning at the end of marking, keeping the second STW very short.

Practice Pause time

Call runtime.GC(), then read the last pause with runtime.ReadMemStats: m.PauseNs[(m.NumGC+255)%256]. Print whether the pause was shorter than one second (< 1e9).

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    runtime.GC()
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    son := m.PauseNs[(m.NumGC+255)%256]
    fmt.Println(son < 1e9)
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the write barrier active?

  • Always
  • Only during STW
  • Never
  • Only during the mark phase Correct answer

Explanation: The barrier watches pointer writes while marking runs; when the GC isn't running it is off and costs nothing.

2 GC trace

Question
GODEBUG=____=1 ./app
Answer
GODEBUG=gctrace=1 ./app

Explanation: gctrace=1 writes timings and heap sizes for every GC cycle to stderr.

3 GC phase

Term Meaning
STW 1 Turn marking on
Concurrent marking While the program runs
STW 2 Finish marking
Sweeping Lazy, during allocation

All lessons in Expert