in e2e-examples/gcs/sample/channel_manager.cc [47:72]
ChannelHandle ChannelManager::GetHandle() {
absl::MutexLock l(&lock_);
// Finds the channel with the least in-use count.
ChannelState* candidate = nullptr;
size_t min_in_use_count = SIZE_MAX;
for (auto& cs : channel_states_) {
if (cs.in_use_count < min_in_use_count) {
candidate = &cs;
min_in_use_count = cs.in_use_count;
}
}
// Should we need to create a new channel? It would create
// a new one when there is no idle channel and a pool is not full yet.
// This lazy channel creation is helpful to avoid underutilized channels.
if (candidate == nullptr || (candidate->in_use_count > 0 &&
channel_states_.size() < max_channel_count_)) {
channel_states_.push_back(ChannelState{channel_creator_(), 0});
candidate = &channel_states_.back();
}
candidate->in_use_count += 1;
channel_handle_count_ += 1;
return ChannelHandle(this, candidate->channel);
}