github.com/weaviate/weaviate@v1.24.6/adapters/repos/db/vector/hnsw/visited/pool.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package visited
    13  
    14  import (
    15  	"sync"
    16  )
    17  
    18  type Pool struct {
    19  	sync.Mutex
    20  	listSetSize int
    21  	listSets    []ListSet
    22  }
    23  
    24  // NewPool creates a new pool with specified size.
    25  // listSetSize specifies the size of a list at creation time point
    26  func NewPool(size int, listSetSize int) *Pool {
    27  	p := &Pool{
    28  		listSetSize: listSetSize,
    29  		listSets:    make([]ListSet, size), // make enough room
    30  	}
    31  
    32  	for i := 0; i < size; i++ {
    33  		p.listSets[i] = NewList(listSetSize)
    34  	}
    35  
    36  	return p
    37  }
    38  
    39  // Borrow return a free list
    40  func (p *Pool) Borrow() ListSet {
    41  	p.Lock()
    42  
    43  	if n := len(p.listSets); n > 0 {
    44  		l := p.listSets[n-1]
    45  		p.listSets[n-1].free() // prevent memory leak
    46  		p.listSets = p.listSets[:n-1]
    47  		p.Unlock()
    48  
    49  		return l
    50  	}
    51  	p.Unlock()
    52  	return NewList(p.listSetSize)
    53  }
    54  
    55  // Return list l to the pool
    56  // The list l might be thrown if l.Len() > listSetSize*1.10
    57  func (p *Pool) Return(l ListSet) {
    58  	n := l.Len()
    59  	if n < p.listSetSize || n > p.listSetSize*11/10 { // 11/10 could be tuned
    60  		return
    61  	}
    62  	l.Reset()
    63  
    64  	p.Lock()
    65  	defer p.Unlock()
    66  
    67  	p.listSets = append(p.listSets, l)
    68  }
    69  
    70  // Destroy and empty pool
    71  func (p *Pool) Destroy() {
    72  	p.Lock()
    73  	defer p.Unlock()
    74  	for i := range p.listSets {
    75  		p.listSets[i].free()
    76  	}
    77  
    78  	p.listSets = nil
    79  }