Manage ownership and backpressure
Manage ownership and backpressure
Backpressure slows producers when consumers cannot keep up. A finite buffer absorbs short bursts, not unlimited work. Sending a slice copies its descriptor, not its backing array. Either transfer exclusive ownership or send an independent snapshot.
package main
import ( "fmt")
func main() { c := make(chan []int, 1) data := []int{1, 2} snapshot := append([]int(nil), data...) c <- snapshot data[0] = 9 fmt.Println(<-c, data)}The copy has independent integer storage. Pointer-bearing elements may need deeper copying. For ownership transfer instead, stop accessing all aliases after sending until ownership is returned through synchronization. Closing a channel does not free objects referenced elsewhere.
Expected output:
[1 2] [9 2]Choose an explicit full-queue policy
package main
import ( "fmt")
func offer(q chan<- int, n int) bool { select { case q <- n: return true default: return false }}func main() { q := make(chan int, 2) fmt.Println(offer(q, 1), offer(q, 2), offer(q, 3)) fmt.Println(<-q) fmt.Println(offer(q, 4)) close(q) for n := range q { fmt.Println(n) }}Offer rejects the third item because both slots are occupied. The producer controls closure. In production choose blocking with cancellation, an overload error, permitted shedding or bounded durable queuing. len(q) is not a reservation: occupancy can change before send. Measure depth, wait time and rejects.
Expected output:
true true false1true24Try it locally
Transfer a slice to a worker that doubles each element and returns ownership through a result channel. Read only after receiving it back. Print [4 6].
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 08: Manage ownership and backpressure
Check the lesson objective before moving on.
What does sending a slice copy?
Why use select with default to offer work?