github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/socket/pool.go (about)

     1  // Copyright 2020 Asim Aslam
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // Original source: github.com/micro/go-micro/v3/util/socket/pool.go
    16  
    17  package socket
    18  
    19  import (
    20  	"sync"
    21  )
    22  
    23  type Pool struct {
    24  	sync.RWMutex
    25  	pool map[string]*Socket
    26  }
    27  
    28  func (p *Pool) Get(id string) (*Socket, bool) {
    29  	// attempt to get existing socket
    30  	p.RLock()
    31  	socket, ok := p.pool[id]
    32  	if ok {
    33  		p.RUnlock()
    34  		return socket, ok
    35  	}
    36  	p.RUnlock()
    37  
    38  	// save socket
    39  	p.Lock()
    40  	defer p.Unlock()
    41  	// double checked locking
    42  	socket, ok = p.pool[id]
    43  	if ok {
    44  		return socket, ok
    45  	}
    46  	// create new socket
    47  	socket = New(id)
    48  	p.pool[id] = socket
    49  
    50  	// return socket
    51  	return socket, false
    52  }
    53  
    54  func (p *Pool) Release(s *Socket) {
    55  	p.Lock()
    56  	defer p.Unlock()
    57  
    58  	// close the socket
    59  	s.Close()
    60  	delete(p.pool, s.id)
    61  }
    62  
    63  // Close the pool and delete all the sockets
    64  func (p *Pool) Close() {
    65  	p.Lock()
    66  	defer p.Unlock()
    67  	for id, sock := range p.pool {
    68  		sock.Close()
    69  		delete(p.pool, id)
    70  	}
    71  }
    72  
    73  // NewPool returns a new socket pool
    74  func NewPool() *Pool {
    75  	return &Pool{
    76  		pool: make(map[string]*Socket),
    77  	}
    78  }