Sync Once Panic Marks Init Done

A panic inside sync.Once.Do still marks the Once done, so later calls skip the init and a failed initialization is never retried.

GoResilience

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once
	var calls int

	// a panic mid-init: Do considers f already run and never retries it
	runInit := func() {
		calls++
		panic("config source unavailable")
	}

	func() {
		defer func() {
			if r := recover(); r != nil {
				fmt.Println("first Do panicked:", r)
			}
		}()
		once.Do(runInit)
	}()

	// the second call returns immediately: done is already marked while init is still missing
	once.Do(runInit)
	fmt.Println("init attempts:", calls)
}

What the code does

The plain reading: it comes down to the function main, doing all the work.

Cleanup is attached with defer, so it runs on every exit path of the function.

What to watch for

  • The runtime is the only requirement — no packages, no install.

Applying it

Signature: func main()

The run emits 2 labeled sections — first Do panicked:, init attempts: — one per step.

Statements that carry the weight

if r := recover(); r != nil {
	fmt.Println("first Do panicked:", r)
}
panic("config source unavailable")
var once sync.Once

Interactive Tools for This Topic

FAQ

What does Sync Once Panic Marks Init Done print when run?
Run it as a complete program — the output lines carry labels such as `first Do panicked:`, `init attempts:`.