Overview of the buffer channel

In Golang, to get around the blocking nature of the channel, we can use a buffer channel. Keep in mind that the blocking nature occurs in the buffer channel when the buffer capacity is full.

A channel without any capacity is also called an unbuffered channel. In other words, it indicates that sends are only accepted if the corresponding receive is ready to receive the value of the sending goroutine. On the other hand, buffered channels accept a limited number of values without a corresponding receiver for those values. Simply put, a buffered channel is like a queue, and it will hold the number of values mentioned while declaring the channel without creating any blockages.

The buffered channels in Golang work in FIFO (first-in-first-out) order.

Usage of a buffered channel

There are numerous cases where we can use a buffered channel, but some of the general uses are as follows:

  • We can use buffered channels when we want to aggregate data from several goroutines and process the returned result.
  • We can use the buffered channels when we want to limit the number of processes or open only a specific number of concurrent processes simultaneously.
  • If we don’t need synchronization immediately but will need it later, we can let the sender fill up the buffer first instead of blocking the send. Then the receiver can empty it and process it.

Declare a buffered channel

The syntax used to declare the buffered channel is similar to the syntax used to declare an ordinary channel. The only difference is that it requires another parameter, capacity. We add the capacity as a second parameter in the make function. The final declaration syntax will be in the syntax make(chan int, capacity), as exemplified below:

goChannel := make(chan int, 2)

Let’s look at the working code to understand it in more depth.

Get hands-on with 1200+ tech skills courses.