MCPcopy Create free account
hub / github.com/dadgar/onecache / acquire

Method acquire

onecache/pool.go:167–227  ·  view source on GitHub ↗

Acquire is used to get a connection that is pooled or to return a new connection

(addr net.Addr)

Source from the content-addressed store, hash-verified

165// Acquire is used to get a connection that is pooled or to return a new
166// connection
167func (p *connPool) acquire(addr net.Addr) (*conn, error) {
168 // Check to see if there's a pooled connection available. This is up
169 // here since it should the the vastly more common case than the rest
170 // of the code here.
171 p.Lock()
172 s := addr.String()
173 c := p.pool[s]
174 if c != nil {
175 c.markForUse()
176 p.Unlock()
177 return c, nil
178 }
179
180 // If not (while we are still locked), set up the throttling structure
181 // for this address, which will make everyone else wait until our
182 // attempt is done.
183 var wait chan struct{}
184 var ok bool
185 if wait, ok = p.limiter[addr.String()]; !ok {
186 wait = make(chan struct{})
187 p.limiter[addr.String()] = wait
188 }
189 isLeadThread := !ok
190 p.Unlock()
191
192 // If we are the lead thread, make the new connection and then wake
193 // everybody else up to see if we got it.
194 if isLeadThread {
195 c, err := p.getNewConn(addr)
196 p.Lock()
197 delete(p.limiter, addr.String())
198 close(wait)
199 if err != nil {
200 p.Unlock()
201 return nil, err
202 }
203
204 p.pool[addr.String()] = c
205 p.Unlock()
206 return c, nil
207 }
208
209 // Otherwise, wait for the lead thread to attempt the connection
210 // and use what's in the pool at that point.
211 select {
212 case <-p.shutdownCh:
213 return nil, fmt.Errorf("rpc error: shutdown")
214 case <-wait:
215 }
216
217 // See if the lead thread was able to get us a connection.
218 p.Lock()
219 if c := p.pool[addr.String()]; c != nil {
220 c.markForUse()
221 p.Unlock()
222 return c, nil
223 }
224

Callers 1

getClientMethod · 0.95

Calls 2

getNewConnMethod · 0.95
markForUseMethod · 0.80

Tested by

no test coverage detected