|
| 1 | +package pool |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + "sync/atomic" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +// Global time cache updated every 50ms by background goroutine. |
| 10 | +// This avoids expensive time.Now() syscalls in hot paths like getEffectiveReadTimeout. |
| 11 | +// Max staleness: 50ms, which is acceptable for timeout deadline checks (timeouts are typically 3-30 seconds). |
| 12 | +var globalTimeCache struct { |
| 13 | + nowNs atomic.Int64 |
| 14 | + lock sync.Mutex |
| 15 | + started bool |
| 16 | + stop chan struct{} |
| 17 | + subscribers int32 |
| 18 | +} |
| 19 | + |
| 20 | +func subscribeToGlobalTimeCache() { |
| 21 | + globalTimeCache.lock.Lock() |
| 22 | + globalTimeCache.subscribers += 1 |
| 23 | + globalTimeCache.lock.Unlock() |
| 24 | +} |
| 25 | + |
| 26 | +func unsubscribeFromGlobalTimeCache() { |
| 27 | + globalTimeCache.lock.Lock() |
| 28 | + globalTimeCache.subscribers -= 1 |
| 29 | + globalTimeCache.lock.Unlock() |
| 30 | +} |
| 31 | + |
| 32 | +func startGlobalTimeCache() { |
| 33 | + globalTimeCache.lock.Lock() |
| 34 | + if globalTimeCache.started { |
| 35 | + globalTimeCache.lock.Unlock() |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + globalTimeCache.started = true |
| 40 | + globalTimeCache.nowNs.Store(time.Now().UnixNano()) |
| 41 | + globalTimeCache.stop = make(chan struct{}) |
| 42 | + globalTimeCache.lock.Unlock() |
| 43 | + // Start background updater |
| 44 | + go func() { |
| 45 | + ticker := time.NewTicker(50 * time.Millisecond) |
| 46 | + defer ticker.Stop() |
| 47 | + |
| 48 | + for range ticker.C { |
| 49 | + select { |
| 50 | + case <-globalTimeCache.stop: |
| 51 | + return |
| 52 | + default: |
| 53 | + } |
| 54 | + globalTimeCache.nowNs.Store(time.Now().UnixNano()) |
| 55 | + } |
| 56 | + }() |
| 57 | +} |
| 58 | + |
| 59 | +// stopGlobalTimeCache stops the global time cache if there are no subscribers. |
| 60 | +// This should only be called when the last subscriber is removed. |
| 61 | +func stopGlobalTimeCache() { |
| 62 | + globalTimeCache.lock.Lock() |
| 63 | + if !globalTimeCache.started || globalTimeCache.subscribers > 0 { |
| 64 | + globalTimeCache.lock.Unlock() |
| 65 | + return |
| 66 | + } |
| 67 | + globalTimeCache.started = false |
| 68 | + close(globalTimeCache.stop) |
| 69 | + globalTimeCache.lock.Unlock() |
| 70 | +} |
| 71 | + |
| 72 | +func init() { |
| 73 | + startGlobalTimeCache() |
| 74 | +} |
0 commit comments