diff options
| author | unwox <me@unwox.com> | 2025-01-27 16:29:14 +0600 |
|---|---|---|
| committer | unwox <me@unwox.com> | 2025-01-27 16:41:01 +0600 |
| commit | c71a1b5ab5d7fbbf4613f0e130a205134875092f (patch) | |
| tree | d6d3ceb44c1b5b818c95d83c61034c7f07756ec7 /pool.go | |
| parent | 34cc55a0fe7e10e12cabac4654898762095b6043 (diff) | |
implement DB connections pooling to mitigate blocking nature of mattn/sqlite3
Diffstat (limited to 'pool.go')
| -rw-r--r-- | pool.go | 42 |
1 files changed, 42 insertions, 0 deletions
@@ -0,0 +1,42 @@ +package main + +import ( + "sync" +) + +const MAX_POOL_SIZE = 50 + +// Pool is a simple pool implementation which grows (up to MAX_POOL_SIZE) when +// needed. +type Pool[T any] struct { + New func() (*T, error) + pool [MAX_POOL_SIZE]*T + size int8 + mu sync.Mutex +} + +// Get returns an instance of T from the pool if it's has one. When it doesn't +// - a new instance is created and returned. +func (p *Pool[T]) Get() (*T, error) { + p.mu.Lock() + defer p.mu.Unlock() + last := p.size - 1 + if last < 0 { + return p.New() + } + res := p.pool[last] + p.pool[last] = nil + p.size = last + return res, nil +} + +// Put returns an instance of T to the pool. If the pool is full - does nothing. +func (p *Pool[T]) Put(item *T) { + p.mu.Lock() + defer p.mu.Unlock() + if p.size + 1 > MAX_POOL_SIZE { + return + } + p.pool[p.size] = item + p.size = p.size + 1 +} |
