Skip to content

Commit 2ce9bef

Browse files
committed
fix: Resolve a potential race condition with the token pool size
1 parent dbd8bab commit 2ce9bef

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

internal/token/token_pool.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,15 @@ import (
66

77
// Pool provides a thread-safe pool of tokens.
88
type Pool struct {
9-
pool map[string]*Token
10-
poolSize int
11-
mu sync.RWMutex
9+
pool map[string]*Token
10+
mu sync.RWMutex
1211
}
1312

1413
// NewPool creates a new token pool with some pre-allocated common tokens.
1514
func NewPool() *Pool {
1615
p := &Pool{
17-
pool: make(map[string]*Token),
18-
poolSize: 0,
19-
mu: sync.RWMutex{},
16+
pool: make(map[string]*Token),
17+
mu: sync.RWMutex{},
2018
}
2119

2220
commonTokens := []struct {
@@ -36,7 +34,6 @@ func NewPool() *Pool {
3634

3735
for _, t := range commonTokens {
3836
p.pool[t.atom] = NewToken(t.atom, t.tokenType)
39-
p.poolSize++
4037
}
4138

4239
return p
@@ -48,15 +45,21 @@ func (p *Pool) GetToken(atom string, tokenType Type) *Token {
4845
return token
4946
}
5047

51-
return NewToken(atom, tokenType)
48+
p.mu.Lock()
49+
defer p.mu.Unlock()
50+
51+
token := NewToken(atom, tokenType)
52+
p.pool[atom] = token
53+
54+
return token
5255
}
5356

5457
// GetPoolSize returns the current size of the pool.
5558
func (p *Pool) GetPoolSize() int {
5659
p.mu.RLock()
5760
defer p.mu.RUnlock()
5861

59-
return p.poolSize
62+
return len(p.pool)
6063
}
6164

6265
func (p *Pool) getFromPool(atom string) (*Token, bool) {

0 commit comments

Comments
 (0)