Skip to content

Commit

Permalink
Simplify IDGenerator and reduce collission rate
Browse files Browse the repository at this point in the history
Since offset is always truncated to s.numBuckets, atomic.Add could be
used instead of atomic.Load + atomic.Swap

Also offsetting bucket by 1 does not give lot's of space for collission
avoidance.
If first call hits bucket that is fully in use, second call going to share same bucket with first call.
  • Loading branch information
dkropachev committed Aug 8, 2024
1 parent 009034a commit a0de29d
Showing 1 changed file with 2 additions and 7 deletions.
9 changes: 2 additions & 7 deletions internal/streams/streams.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,8 @@ func streamFromBucket(bucket, streamInBucket int) int {
}

func (s *IDGenerator) GetStream() (int, bool) {
// based closely on the java-driver stream ID generator
// avoid false sharing subsequent requests.
offset := atomic.LoadUint32(&s.offset)
for !atomic.CompareAndSwapUint32(&s.offset, offset, (offset+1)%s.numBuckets) {
offset = atomic.LoadUint32(&s.offset)
}
offset = (offset + 1) % s.numBuckets
// Reduce collisions by offsetting the starting point
offset := atomic.AddUint32(&s.offset, 1)

for i := uint32(0); i < s.numBuckets; i++ {
pos := int((i + offset) % s.numBuckets)
Expand Down

0 comments on commit a0de29d

Please sign in to comment.