From c71a1b5ab5d7fbbf4613f0e130a205134875092f Mon Sep 17 00:00:00 2001 From: unwox Date: Mon, 27 Jan 2025 16:29:14 +0600 Subject: implement DB connections pooling to mitigate blocking nature of mattn/sqlite3 --- pool.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 pool.go (limited to 'pool.go') diff --git a/pool.go b/pool.go new file mode 100644 index 0000000..06e355c --- /dev/null +++ b/pool.go @@ -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 +} -- cgit v1.2.3