How to get the capacity of one channel?

Following is sample code for golang.

package main

import "fmt"

func main() {
	ch0 := make(chan string)
	fmt.Println(cap(ch0))
	ch3 := make(chan string, 3)
	fmt.Println(cap(ch3))
}

// =>
// 0
// 3

We are not the public API to get the @capacity ivar, right?

Crystal Channel doesn’t expose such API. Generally capacity applies to buffered channels only, where it represents the number of elements channel can hold, and it shouldn’t be confused with size. I don’t know what would be the use case where you would require such information, but you can get this info by monkey patching the Channel class.

Note: Monkey patching stdlib isn’t a good practice and is something which should be applied with extreme caution.

class Channel(T)
  def capacity : Int32
    (queue = @queue) ? queue.@capacity : 0
  end
end

And now you can get the capacity

ch0 = Channel(Nil).new
puts ch0.capacity # => 0

ch3 = Channel(Nil).new(3)
puts ch3.capacity # => 3

HIH

2 Likes

No really, just because i found golang exposed this API, so, it probably useful for users from go, should we add this feature?

Yeah, sure it will be good to raise a feature request and have it open for discussion, and see if community and/or core team agrees to extend Channel class to add some api which Returns Maximum capacity of the Channel.

Reference could be GoLang API and Concurrent Ruby

1 Like

Just note that without an actual use case the chances of adding this will be very small.

I could imagine 1 use case would be gathering/monitoring channel metrics, and maybe automating channel capacity or spawning more process w/ more channels, depending on demand.

2 Likes