Non-Blocking Queue Ops With select default

A select with a default case turns channel sends and receives into non-blocking operations, dropping jobs when a bounded queue is already full.

GoResilience

Code

gosnippet
36 lines
package main

import "fmt"

func main() {
	queue := make(chan int, 2)

	// Queue not full: non-blocking sends succeed one by one
	for job := 1; job <= 2; job++ {
		select {
		case queue <- job:
			fmt.Println("accepted:", job)
		default:
			fmt.Println("queue full, dropped:", job)
		}
	}

	// Queue full: default kicks in - drop instead of blocking the whole goroutine
	select {
	case queue <- 3:
		fmt.Println("accepted:", 3)
	default:
		fmt.Println("queue full, dropped:", 3)
	}

	// Non-blocking receives drain the queue, then a final default probe confirms it is empty
	for {
		select {
		case job := <-queue:
			fmt.Println("processed:", job)
		default:
			fmt.Println("queue drained")
			return
		}
	}
}

The flow of the file

Non-Blocking Queue Ops With select default comes down to the function main.

Repetition is confined to for job := 1; job <= 2; job++ — the rest of the file is straight-line.

Putting it to use

Running the file prints labeled results such as accepted:, queue full, dropped:, processed: — each operation’s effect is visible in the output.

Core lines

queue := make(chan int, 2)

Interactive Tools for This Topic

FAQ

What does Non-Blocking Queue Ops With select default print when run?
Run it as a complete program — the output lines carry labels such as `accepted:`, `queue full, dropped:`, `processed:`.