Skip to content

Optimize BlockOnLock retry loop to eliminate per-iteration allocations#10444

Merged
coffeegoddd merged 3 commits intodb/lockfrom
copilot/sub-pr-10442
Feb 6, 2026
Merged

Optimize BlockOnLock retry loop to eliminate per-iteration allocations#10444
coffeegoddd merged 3 commits intodb/lockfrom
copilot/sub-pr-10442

Conversation

Copy link
Copy Markdown

Copilot AI commented Feb 6, 2026

Addresses feedback on #10442 to reduce GC churn in the BlockOnLock retry loop. The original implementation allocated a new timer on each iteration via time.After(), causing unnecessary memory pressure when locks are held for extended periods.

Changes

  • Added lockRetryInterval constant: Extracts hardcoded 10ms retry interval into a named constant for clarity and tunability
  • Replaced time.After with lazy-initialized time.Ticker: Single ticker instance reused across all retries, eliminated per-iteration allocations
  • Optimized fast path: Ticker creation deferred until first lock failure, avoiding overhead when lock is immediately available

Before

for {
    err = lock.TryLock()
    if err == nil {
        break
    }
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    case <-time.After(10 * time.Millisecond):  // New allocation each iteration
    }
}

After

var ticker *time.Ticker
defer func() {
    if ticker != nil {
        ticker.Stop()
    }
}()
for {
    err = lock.TryLock()
    if err == nil {
        break
    }
    if ticker == nil {
        ticker = time.NewTicker(lockRetryInterval)  // Allocate once, reuse
    }
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    case <-ticker.C:
    }
}

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 2 commits February 6, 2026 22:31
Co-authored-by: coffeegoddd <43383835+coffeegoddd@users.noreply.github.com>
Co-authored-by: coffeegoddd <43383835+coffeegoddd@users.noreply.github.com>
Copilot AI changed the title [WIP] WIP Address feedback on lock option implementation Optimize BlockOnLock retry loop to eliminate per-iteration allocations Feb 6, 2026
Copilot AI requested a review from coffeegoddd February 6, 2026 22:33
@coffeegoddd coffeegoddd marked this pull request as ready for review February 6, 2026 22:33
@coffeegoddd coffeegoddd merged commit bcd9673 into db/lock Feb 6, 2026
@coffeegoddd coffeegoddd deleted the copilot/sub-pr-10442 branch February 6, 2026 22:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants